AJAX: Difference between revisions

The educational technology and digital learning wiki
Jump to navigation Jump to search
Line 1: Line 1:
== Definition ==
== Definition ==


According to [[http://en.wikipedia.org/wiki/AJAX Wikipedia]]: {{quotation | Ajax, shorthand for Asynchronous JavaScript and XML, is a web development technique for creating interactive web applications. The intent is to make web pages feel more responsive by exchanging small amounts of data with the server behind the scenes, so that the entire web page does not have to be reloaded each time the user requests a change. This is meant to increase the web page's interactivity, speed, and usability.}}, , retrieved 14:57, 9 February 2007 (MET)
According to [[http://en.wikipedia.org/wiki/AJAX Wikipedia]]: {{quotation | Ajax, shorthand for Asynchronous JavaScript and XML, is a web development technique for creating interactive web applications. The intent is to make web pages feel more responsive by exchanging small amounts of data with the server behind the scenes, so that the entire web page does not have to be reloaded each time the user requests a change. This is meant to increase the web page's interactivity, speed, and usability.}}, , retrieved 14:59, 9 February 2007 (MET)


The Ajax technique uses a combination of:
The Ajax technique uses a combination of:
Line 11: Line 11:


== A simple example ==
== A simple example ==
AJAX is really simple. The difficult part is to write really good interfaces
(see toolkits in the links section) and to do something with these data on the server side ...


; HTML/JavAscript
; HTML/JavAscript


<nowiki>
<nowiki>
<html>
<html>
  <head>
  <head>
    <title>Simple Ajax example</title>
    <title>Simple Ajax example</title>
    <script type="text/javascript" language="javascript">
    <script type="text/javascript" language="javascript">
 
var url;
var url;
var table;
var table;
 
function init () {
function init () {
  url = "ajax1.php";
  url = "ajax1.php";
// url = "ajax-debug.php";
  // url = "ajax-debug.php";
  table = document.getElementById("table1");
  table = document.getElementById("table1");
}
}
 
 
 
function makeRequest(element) {
function makeRequest(element) {
  // This function is called from the HTML code below
  // This function is called from the HTML code below
  // element is the DOM element (tag on which the user clicked)
  // element is the DOM element (tag on which the user clicked)
 
  var http_request = false;
  var http_request = false;
 
 
  // ---- Mozilla, Safari, etc. browsers
  // ---- Mozilla, Safari, etc. browsers
  if (window.XMLHttpRequest) {  
  if (window.XMLHttpRequest) {  
    http_request = new XMLHttpRequest();
    http_request = new XMLHttpRequest();
    // This will make sure that the server response claims to be XML (in case we retrieve something else)
    // This will make sure that the server response claims to be XML (in case we retrieve something else)
    if (http_request.overrideMimeType) {
    if (http_request.overrideMimeType) {
      http_request.overrideMimeType('text/xml');
      http_request.overrideMimeType('text/xml');
     
     
    }
    }
    // ---- IE browsers
    // ---- IE browsers
  } else if (window.ActiveXObject) {  
  } else if (window.ActiveXObject) {  
    try {
    try {
      http_request = new ActiveXObject("Msxml2.XMLHTTP");
      http_request = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
    } catch (e) {
      try {
      try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
http_request = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e) {}
      } catch (e) {}
    }
    }
  }
  }
 
 
  // ---- abort if there is no reply
  // ---- abort if there is no reply
  if (!http_request) {
  if (!http_request) {
    alert('Giving up :( Cannot create an XMLHTTP instance');
    alert('Giving up :( Cannot create an XMLHTTP instance');
    return false;
    return false;
  }
  }
 
 
  // We register the function that will deal with a reply
  // We register the function that will deal with a reply
  http_request.onreadystatechange = function() { processServerReply(http_request); };
  http_request.onreadystatechange = function() { processServerReply(http_request); };
 
 
  // This lines starts building the request - don't think that a GET request would work (?)
  // This lines starts building the request - don't think that a GET request would work (?)
  http_request.open('POST', url, true);
  http_request.open('POST', url, true);
  // Contents WE send from here will be urlencoded
  // Contents WE send from here will be urlencoded
  http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
 
 
  // here we extract the contents of tag on which the user clicked
  // here we extract the contents of tag on which the user clicked
  user_pref    = element.innerHTML;
  user_pref    = element.innerHTML;
  // This is the content of the request
  // This is the content of the request
  // alert(user_pref);
  // alert(user_pref);
  user_request = "user_pref_fruit=" + user_pref;
  user_request = "user_pref_fruit=" + user_pref;
 
 
  // We send the data - data are query strings
  // We send the data - data are query strings
  http_request.send(user_request);
  http_request.send(user_request);
 
 
}
}
 
 
 
function processServerReply(http_request) {
function processServerReply(http_request) {
 
  if (http_request.readyState == 4) {
  if (http_request.readyState == 4) {
    if (http_request.status == 200) {
    if (http_request.status == 200) {
      // We tell the server that we want to deal with XML as a DOM Document !!
      // We tell the server that we want to deal with XML as a DOM Document !!
      replyXML = http_request.responseXML;
      replyXML = http_request.responseXML;
      treatResponse (replyXML);
      treatResponse (replyXML);
      // displayResponse (replyXML);
      // displayResponse (replyXML);
     
     
    } else {
    } else {
      alert('There was a problem with the request.');
      alert('There was a problem with the request.');
    }
    }
  }
  }
 
 
}
}
 
// This will change the HTML contents of the page
// This will change the HTML contents of the page
function treatResponse (reply) {
function treatResponse (reply) {
  // reply is a XML DOM datastructure !!
  // reply is a XML DOM datastructure !!
  // extract some XML - we know that it is in an "answer" tag
  // extract some XML - we know that it is in an "answer" tag
  // DOM HTML will not work, it's XML here  
  // DOM HTML will not work, it's XML here  
  var answer = reply.getElementsByTagName('answer').item(0).firstChild.nodeValue;
  var answer = reply.getElementsByTagName('answer').item(0).firstChild.nodeValue;
 
  // new tr, td elements
  // new tr, td elements
  var element_tr = document.createElement("tr");
  var element_tr = document.createElement("tr");
  var element_td = document.createElement("td");
  var element_td = document.createElement("td");
  // contents for the td element
  // contents for the td element
  var text    = document.createTextNode(answer);
  var text    = document.createTextNode(answer);
  element_td.appendChild(text);
  element_td.appendChild(text);
  element_tr.appendChild(element_td);
  element_tr.appendChild(element_td);
  table.appendChild(element_tr);
  table.appendChild(element_tr);
}
}
 
// just for debugging, will open up a popup window. Useful if you tell the php to send debugging infos...
// just for debugging, will open up a popup window. Useful if you tell the php to send debugging infos...
function displayResponse (reply) {
function displayResponse (reply) {
  win=window.open("","Results","width=250,height=300,status=1,resizable=1,scrollbars=1");
  win=window.open("","Results","width=250,height=300,status=1,resizable=1,scrollbars=1");
  win.document.open();
  win.document.open();
  win.document.write(reply);
  win.document.write(reply);
  win.document.close();
  win.document.close();
}
}
 
 
  </script>
</script>
 
 
</head>
</head>
 
  <body onload="init()">
  <body onload="init()">
    <h1>Simple Ajax example</h1>
    <h1>Simple Ajax example</h1>
 
    <strong>Please</strong> click on a fruit:
    <strong>Please</strong> click on a fruit:
 
    <ul>
    <ul>
      <li>I like
      <li>I like
<span
<span
  style="cursor: pointer; text-decoration: underline"
  style="cursor: pointer; text-decoration: underline"
  onclick="makeRequest(this)">
  onclick="makeRequest(this)">
  apples
  apples
      </li>
      </li>
      <li>I like
      <li>I like
<span
<span
  style="cursor: pointer; text-decoration: underline"
  style="cursor: pointer; text-decoration: underline"
  onclick="makeRequest(this)">
  onclick="makeRequest(this)">
  oranges
  oranges
      </li>
      </li>
 
      <li>I like
      <li>I like
<span
<span
  style="cursor: pointer; text-decoration: underline"
  style="cursor: pointer; text-decoration: underline"
  onclick="makeRequest(this)">
  onclick="makeRequest(this)">
  bananas
  bananas
 
</span>
</span>
      </li>
      </li>
 
    </ul>
    </ul>
 
    <hr>
    <hr>
  Dialog history:
Dialog history:
   
      
     <table border id="table1">
  <table border id="table1">
 
<tr>
<tr>
  <!-- one of (TD TH) -->
  <!-- one of (TD TH) -->
  <th>Server replies</th>
  <th>Server replies</th>
</tr>
</tr>
 
    </table>
    </table>
</nowiki>
</nowiki>
 
; PHP
; PHP
<?php
<nowiki>
  <?php
  error_reporting(E_ALL);
  error_reporting(E_ALL);
  header ("Content-type: application/xml");   
  header ("Content-type: application/xml");   
  echo '<?xml version="1.0" encoding="ISO-8859-1" ?>';
  echo '<?xml version="1.0" encoding="ISO-8859-1" ?>';
 
  if (array_key_exists('user_pref_fruit', $_POST))   
  if (array_key_exists('user_pref_fruit', $_POST))   
   { $user_pref  = $_POST['user_pref_fruit']; }
   { $user_pref  = $_POST['user_pref_fruit']; }
   else  
   else  
     $user_pref="nothing";
     $user_pref="nothing";
 
  echo "<answer>";
  echo "<answer>";
  echo "Oh you like " . $user_pref . " !";
  echo "Oh you like " . $user_pref . " !";
  // echo "Oh you like " . $user_pref . " !" . " - Query String=" .  $_SERVER["QUERY_STRING"];
  // echo "Oh you like " . $user_pref . " !" . " - Query String=" .  $_SERVER["QUERY_STRING"];
  echo "</answer>";
  echo "</answer>";
 
?>  
?>  
 
</nowiki>


== Software ==
== Software ==
Line 197: Line 200:


;Dojo (free software)
;Dojo (free software)
* {{quotation | dojo is the Open Source Javascript toolkit that makes professional web development better, easier, and faster}} (retrieved 14:57, 9 February 2007 (MET))
* {{quotation | dojo is the Open Source Javascript toolkit that makes professional web development better, easier, and faster}} (retrieved 14:59, 9 February 2007 (MET))
* [http://dojotoolkit.org/ dojo toolkit homepage]
* [http://dojotoolkit.org/ dojo toolkit homepage]
* Dojo manual: http://manual.dojotoolkit.org/WikiHome
* Dojo manual: http://manual.dojotoolkit.org/WikiHome
Line 203: Line 206:


; Aculo (free software)
; Aculo (free software)
* {{quotation | script.aculo.us provides you with easy-to-use, cross-browser user interface JavaScript libraries to make your web sites and web applications fly.}} (retrieved 14:57, 9 February 2007 (MET))
* {{quotation | script.aculo.us provides you with easy-to-use, cross-browser user interface JavaScript libraries to make your web sites and web applications fly.}} (retrieved 14:59, 9 February 2007 (MET))
* [http://script.aculo.us/ Aculo Home Page]
* [http://script.aculo.us/ Aculo Home Page]
* [http://prototype.conio.net/ Prototype JavaScript framework website].
* [http://prototype.conio.net/ Prototype JavaScript framework website].
Line 209: Line 212:


; Prototype.js library
; Prototype.js library
* {{quotation| This amazingly well thought and well written piece of standards-compliant code takes a lot of the burden associated with creating rich, highly interactive web pages that characterize the Web 2.0 off your back.}} (retrieved 14:57, 9 February 2007 (MET))
* {{quotation| This amazingly well thought and well written piece of standards-compliant code takes a lot of the burden associated with creating rich, highly interactive web pages that characterize the Web 2.0 off your back.}} (retrieved 14:59, 9 February 2007 (MET))
* [http://www.sergiopereira.com/articles/prototype.js.html Unofficial Prototype documentation] by Sergio Pereira
* [http://www.sergiopereira.com/articles/prototype.js.html Unofficial Prototype documentation] by Sergio Pereira
* Amy Hoy's [http://slash7.com/cheats/scriptaculous_fx1.pdf Cheat Sheet]
* Amy Hoy's [http://slash7.com/cheats/scriptaculous_fx1.pdf Cheat Sheet]

Revision as of 14:59, 9 February 2007

Definition

According to [Wikipedia]: “Ajax, shorthand for Asynchronous JavaScript and XML, is a web development technique for creating interactive web applications. The intent is to make web pages feel more responsive by exchanging small amounts of data with the server behind the scenes, so that the entire web page does not have to be reloaded each time the user requests a change. This is meant to increase the web page's interactivity, speed, and usability.”, , retrieved 14:59, 9 February 2007 (MET)

The Ajax technique uses a combination of:

  • XHTML (or HTML) and CSS, for marking up and styling information.
  • The DOM accessed with a client-side scripting language, usually ECMAScript (JavaScript)
  • The XMLHttpRequest object is used to exchange data asynchronously with the web server.
  • XML is sometimes used as the format for transferring data between the server and client.

A simple example

AJAX is really simple. The difficult part is to write really good interfaces (see toolkits in the links section) and to do something with these data on the server side ...

HTML/JavAscript

<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 </li> <li>I like <span style="cursor: pointer; text-decoration: underline" onclick="makeRequest(this)"> oranges </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>

; 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>";  ?>

Software

JavaScript toolkits

Dojo (free software)
Aculo (free software)
Prototype.js library
  • “This amazingly well thought and well written piece of standards-compliant code takes a lot of the burden associated with creating rich, highly interactive web pages that characterize the Web 2.0 off your back.” (retrieved 14:59, 9 February 2007 (MET))
  • Unofficial Prototype documentation by Sergio Pereira
  • Amy Hoy's Cheat Sheet
  • Jonathan Snook's Prototype Dissected

Links

References

Technical how-to

  • Vlad Kofman (2007), The Web 2.0 Movement Is Here. But What Does It Mean to You?, Developper.com Atricle, HTML