PREVIOUS UP  Technologies Internet et Education, © TECFA
  13. AJAX

13. AJAX

Asynchronous JavaScript and XML (AJAX) is not a technology in itself, but is a term that describes a "new" approach to using a number of existing technologies together, including: HTML or XHTML, Cascading Style Sheets, JavaScript, The Document Object Model, XML, XSLT, and the XMLHttpRequest object.

Exemple 13-1: AJAX request

Exemple 13-2: AJAX request et pseudo XML response

Exemple 13-3: AJAX request et XML response

On analyse les réponses du serveur en tant que XML DOM en utilisant l’API DOM Core

Code HTML et JavaScript

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>Simple Ajax example</title>
<script type="text/javascript" language="javascript">
var url;
var table;
 
function init () {
  url = "ajax1.php";
 // url = "ajax-debug.php";
  table = document.getElementById("table1");
}
 
function makeRequest(element) {
  // This function is called from the HTML code below
  // element is the DOM element (tag on which the user clicked)
 
  var http_request = false;
  
  // ---- Mozilla, Safari, etc. browsers
  if (window.XMLHttpRequest) { 
    http_request = new XMLHttpRequest();
    // This will make sure that the server response claims to be XML (in case we retrieve something else)
    if (http_request.overrideMimeType) {
      http_request.overrideMimeType('text/xml');
    }
    // ---- IE browsers
  } else if (window.ActiveXObject) { 
    try {
      http_request = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
	     http_request = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e) {}
    }
  }
  
  // ---- abort if there is no reply
  if (!http_request) {
    alert('Giving up :( Cannot create an XMLHTTP instance');
    return false;
  }
  
  // We register the function that will deal with a reply
  http_request.onreadystatechange = function() { processServerReply(http_request); };
  
  // This lines starts building the request - don't think that a GET request would work (?)
  http_request.open('POST', url, true);
  // Contents WE send from here will be urlencoded
  http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  
  // here we extract the contents of tag on which the user clicked
  user_pref    = element.innerHTML;
  // This is the content of the request
  // alert(user_pref);
  user_request = "user_pref_fruit=" + user_pref;
  
  // We send the data - data are query strings
  http_request.send(user_request);
}
 
function processServerReply(http_request) {
 
  if (http_request.readyState == 4) {
    if (http_request.status == 200) {
      // We tell the server that we want to deal with XML as a DOM Document !!
      replyXML = http_request.responseXML;
      treatResponse (replyXML);
      // displayResponse (replyXML);
    } else {
      alert('There was a problem with the request.');
    }
  }
}
 
// This will change the HTML contents of the page
function treatResponse (reply) {
  // reply is a XML DOM datastructure !!
  // extract some XML - we know that it is in an "answer" tag
  // DOM HTML will not work, it's XML here 
  var answer = reply.getElementsByTagName('answer').item(0).firstChild.nodeValue;
 
  // new tr, td elements
  var element_tr = document.createElement("tr");
  var element_td = document.createElement("td");
  // contents for the td element
  var text    = document.createTextNode(answer);
  element_td.appendChild(text);
  element_tr.appendChild(element_td);
  table.appendChild(element_tr);
}
 
// just for debugging, will open up a popup window. Useful if you tell the php to send debugging infos...
function displayResponse (reply) {
  win=window.open("","Results","width=250,height=300,status=1,resizable=1,scrollbars=1");
  win.document.open();
  win.document.write(reply);
  win.document.close();
}
 </script>
 
</head>
  <body onload="init()">
    <h1>Simple Ajax example</h1>
 
    <strong>Please</strong> click on a fruit:
 
    <ul>
      <li>I like
	<span
	  style="cursor: pointer; text-decoration: underline"
	  onclick="makeRequest(this)">
	  apples
	</span>
      </li>
      <li>I like
	<span
	  style="cursor: pointer; text-decoration: underline"
	  onclick="makeRequest(this)">
	  oranges
	</span>
      </li>
      <li>I like
	<span
	  style="cursor: pointer; text-decoration: underline"
	  onclick="makeRequest(this)">
	  bananas
 
	</span>
      </li>
 
    </ul>
 
    <hr>
 Dialog history:
    
   <table border id="table1">
	<tr>
	  <!-- one of (TD TH) -->
	  <th>Server replies</th>
	</tr>
 
    </table>
 
    <hr>
    <strong>Explanations</strong>:
    <p>
    This example is inspired by <a href="http://developer.mozilla.org/en/docs/AJAX:Getting_Started">http://developer.mozilla.org/en/docs/AJAX:Getting_Started</a>
 
It does the following:
    <ul>
      <li>When you click on a fruit it will call a function that grabs the element, extracts its contents and sends it to a php file with a POST argument that goes like  "user_pref_fruit=appeles"</li>
      <li>The server will give some answer that will be put into a DOM document. It's contents are.
<pre>
&lt;?xml version="1.0" encoding="ISO-8859-1" ?&gt;
   &lt;answer&gt;Oh you like  bananas!&lt;/answer&gt;
</pre>
      </li>
      <li>You then can use the XML DOM Code API to take the answer apart .... We just extract the answer and append it to this page.</li>
      <li>The source code for the JS part is in this page (do "View Source") and the PHP part is <a href="ajax1.phps">ajax1.phps</a></li>
      <li>Other examples: see the <a href="./">directory</a></li>
    </ul>
 
 
    <hr>
    <address><a href="mailto:Daniel.Schneider@tecfa.unige.ch">Daniel K. Schneider</a></address>
<!-- Created: Fri Apr 28 09:57:16 CEST 2006 -->
<!-- hhmts start -->
Last modified: Tue Oct 02 20:08:02 Paris, Madrid 2007
<!-- hhmts end -->
  </body>
</html>

Le fichier PHP (ajax1.php)

<?php
error_reporting(E_ALL);
header ("Content-type: application/xml");   
echo '<?xml version="1.0" encoding="ISO-8859-1" ?>';
 
if (array_key_exists('user_pref_fruit', $_POST))  
  { $user_pref  = $_POST['user_pref_fruit']; }
 else 
   $user_pref="nothing";
 
echo "<answer>";
echo "Oh you like " . $user_pref . " !";
// echo "Oh you like " . $user_pref . " !" . " - Query String=" . $_SERVER["QUERY_STRING"];
echo "</answer>";
 
?>

PREVIOUSUP -- TIE