Asynchronous Javascript and XML (AJAX)

Peter Wood

Ajax

XMLHttpRequest example

Form for RSS feeds

<form>
  <input type="button" value="BBC news"
         onClick="outputFeeds(0)" />
  <input type="button" value="Guardian news"
         onClick="outputFeeds(1)" />
  <input type="button" value="New York Times news"
         onClick="outputFeeds(2)" />
</form>

outputFeeds function

function outputFeeds(i) {
  var feed = new Array(
      "http://feeds.bbci.co.uk/news/rss.xml?edition=uk",
      "http://feeds.theguardian.com/theguardian/uk/rss",
      "http://www.nytimes.com/services/xml/rss/nyt/International.xml");
  var doc = loadXMLHTTP(feed[i]);
  var ul = document.getElementById("details");
  ul.innerHTML = feedToList(doc);
}

loadXMLHTTP function

function loadXMLHTTP(url) {
  xmlhttp = new XMLHttpRequest();
  xmlhttp.open("GET", 'proxy.php?url=' + escape(url), false);
  xmlhttp.send(null);
  return xmlhttp.responseXML;
}

proxy.php

<?php

header('Content-type: text/xml; charset=utf-8');

$url = $_GET['url'];
echo file_get_contents($url);

?>

feedToList function

function feedToList(doc) {
  var title;
  var out = "";

  var items = doc.getElementsByTagName("item");
  for (var i = 0; i < items.length; i++) {
    title = items[i].getElementsByTagName("title")[0].firstChild.nodeValue;
    out = out + "<li>" + title + "</li>";
  }
  return out;
}

Google Suggest lookalike

searchSuggest function

var searchReq = getXmlHttpRequestObject();

function searchSuggest() {
 if (searchReq.readyState == 4 || searchReq.readyState == 0) {
  var str = escape(document.getElementById('txtSearch').value);
  searchReq.open("GET", 'searchSuggest.php?search=' + str, true);
  searchReq.onreadystatechange = handleSearchSuggest;
  searchReq.send(null);
 }
}

searchSuggest.php

<?php
header("Content-Type: application/json; charset=utf-8");
...
$suggestions = array("Ajax","ASP","Javascript","JSP","XML","XPath","XSD","XSLT");
$result = array();

// Make sure that a value was sent.
if (isset($_GET['search']) && $_GET['search'] != '') {
   $search = $_GET['search'];
   foreach ($suggestions as $suggestion) {
      // Add each suggestion to the $result array
      if (strpos($suggestion,$search)===0)
         $result[] = $suggestion;
   }
   echo json_encode($result);
}
?>

handleSearchSuggest function

//Called when the AJAX response is returned.
function handleSearchSuggest() {
 if (searchReq.readyState == 4) {
  var ss = document.getElementById('search_suggest');
  ss.innerHTML = '';
  var str = JSON.parse(searchReq.responseText); // PTW modified for JSON
  // For loop to build list of suggestions goes here (next slide)
 }
}

handleSearchSuggest function (for loop)

...
  // Returned suggestions are in array str
  for(i=0; i < str.length; i++) {
   //Build our element string.  This is cleaner using the DOM,
   //but IE doesn't support dynamically added attributes.
   var suggest = '<div onmouseover="javascript:suggestOver(this);" ';
   suggest += 'onmouseout="javascript:suggestOut(this);" ';
   suggest += 'onclick="javascript:setSearch(this.innerHTML);" ';
   suggest += 'class="suggest_link">' + str[i] + '</div>';
   ss.innerHTML += suggest;
  }
...

Mouse over, mouse out and click functions

//Mouse over function
function suggestOver(div_value) {
  div_value.className = 'suggest_link_over';
}
//Mouse out function
function suggestOut(div_value) {
  div_value.className = 'suggest_link';
}
//Click function
function setSearch(value) {
  document.getElementById('txtSearch').value = value;
  document.getElementById('search_suggest').innerHTML = '';
}

Exercise

Links to more information

AJAX is covered in Chapter 9 in [Jacobs]. It is also mentioned in Section 7.3.3 of [Tanenbaum].