9. Asynchronous Javascript and XML (AJAX)


  1. Ajax
  2. XMLHttpRequest example
  3. Form for RSS feeds
  4. outputFeeds function
  5. loadXMLHTTP function
  6. proxy.php
  7. feedToList function
  8. Google Suggest lookalike
  9. searchSuggest function
  10. searchSuggest.php
  11. handleSearchSuggest function
  12. handleSearchSuggest function (for loop)
  13. Mouse over, mouse out and click functions
  14. Exercise
  15. Links to more information

9.1. Ajax

9.2. XMLHttpRequest example

9.3. 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>

9.4. 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);
}

9.5. loadXMLHTTP function

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

9.6. proxy.php

<?php

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

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

?>

9.7. 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;
}

9.8. Google Suggest lookalike

9.9. 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);
 }
}

9.10. 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);
}
?>

9.11. 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)
 }
}

9.12. 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;
  }
...

9.13. 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 = '';
}

9.14. Exercise

9.15. Links to more information

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