A simple AJAX example

The client side (javascript)


<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!--
A simple AJAX example
Author: Elena Machkasova elenam@morris.umn.edu
Last modified: 2/21/11
-->
<script type="text/javascript">
function getInfo(str) {
    var xmlhttp;
    if (str.length==0) {
        document.getElementById("result").innerHTML="";
        return;
    }
    if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else {// unsafe code for IE6, IE5
    //xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
       document.getElementById("result").innerHTML=
           "Your browser doesn't support this function";
       return;
    }
    xmlhttp.onreadystatechange=function() {
         if (xmlhttp.readyState==4 && xmlhttp.status==200) {
           document.getElementById("result").innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET","friend_info.php?friend="+str,true);
    xmlhttp.send();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>CSci 4657: a simple AJAX example</title>
<p>
<form action="">
<label for="name"> Type your friend's name here </label>
<input type="text" id="name" onkeyup="getInfo(this.value)" />
</form>
</p>
<p id="result">

</p>

</body>
</html>

The server side (php)


<?php

// the function returns a string of all elements
// of the array for which a given string is a prefix
function prefixes($str, $array) {
  $result = "";
  foreach ($array as $item) {
    if (strpos($item, $str) === 0) {
      $result = $result." $item";
    }
  }
  return $result;
}

$friends = array (
                  "Amanda" => "Last seen on Feb. 20",
                  "Bob" => "Last seen on Feb. 4",
                  "Bill" => "Logged in",
                  "George" => "Logged in",
                  "Liz" => "Last seen on Dec. 25",
                  "Lory" => "Never logged in"
                  );

$friend = $_GET["friend"];

if (isset($friends[$friend])) {
  print $friends[$friend];
 } else {
  $possibilities = prefixes($friend,array_keys($friends));
  if (strcmp($possibilities,"") === 0) {
    print "No such person: $friend";
  } else {
    print $possibilities;
  }
 }
?>
http://csci1101sp10.morris.umn.edu/~elenam/4657sp11/ajax/ajax_friend_info.html

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.