Introduction to AJAX

From CSE330 Wiki

Jump to: navigation, search

Contents

[edit] Asynchronous JavaScript And XML

AJAX is a way to use existing standards. It provides a framework for javascript to get the data from external servers. Javascript object XMLHttpRequest is used exchange data with other servers without reloading the page. This provides less data transmission between the servers and the clients and makes Internet applications smaller, faster and more user-friendly.

XMLHttpRequest is supported by all modern browsers however there are slight changes (in case of IE, large changes) so for the rest of this module, we will assume Firefox as our browser.

[edit] XMLHttpRequest Object

XMLHttpRequest provides the communication with the remote servers. Hence, the first thing you need is to initialize it.


 var xmlHttp;
 xmlHttp=new XMLHttpRequest();

Once you have an XMLHttpRequest, you can use it to send data to a server. Initially, you need to connect your server side page:

xmlHttp.open("METHOD","REMOTE_URL",ASYNCRONOUS_FLAG);

where METHOD is "GET" or "POST", REMOTE_URL is the page that you want to communicate and ASYNCRONOUS_FLAG is whether the call is going to asyncronous. In asyncronous communication, you can let your client do other things while waiting for server response. Once you have the object initialized, you can then use send method to send your request. Note that, there is not explicit data setting. That is because you send your data withing the url.

xmlHttp.send(null);


XMLHttpRequest object has an attribute readyState that stores the state of the current status.

StateDescription
0The request is not initialized
1The request has been set up
2The request has been sent
3The request is in process
4The request is complete

For example, when a request is sent, the state is set to 3. Every time its state change,the object calls a function specified by the attribute onreadystatechange. So before calling a remote site, you should setup a new function:

xmlHttp.onreadystatechange=function() {
   alert('state changed to '+xmlHttp.readyState);
}

This is where the asyncronousity comes. Once you send a request, you access the response only onreadystatechange function. Meanwhile, your client page can be doing other things. If you are waiting for a response from the server, you should check whether the readyState is 4, corresponding to completed request. The server response is returned at XMLHttpRequest's responseText attribute.

xmlHttp.onreadystatechange=function() {
   if(xmlHttp.readyState==4){
   .... do some cool stuff ...
    }
}

For example, lets assume you have following html file server.html

<html>
<body>
hello world
</body>
</html>

This server page just prints hello world message.

Here is an AJAX implementation that gets the message from the server and prints it.

<html>
<body>
<script>
var xmlHttp;
  xmlHttp=new XMLHttpRequest();

   xmlHttp.open("GET","server.html",true);

   xmlHttp.onreadystatechange=function() {
    if(xmlHttp.readyState==4){
    var pElement=document.getElementById("msg");
     pElement.innerHTML=xmlHttp.responseText;
     }
 }
   xmlHttp.send(null);
</script>
<p id="msg"></p>
</body>
</html>

[edit] Sending Parameters

The parameters are send either in the url (to, for example, a PHP page) or through send function. Consider following PHP code that takes two parameters, multiplies them and return the result.

multiply.php

<html>
<body>
<? echo $_GET["x"]*$_GET["y"]?>
</body>
</html>

We can then use AJAX to get the multiplication of two numbers:

multiply-ajax.php

<html>
<body>
<script>
function multiply (){
  var xmlHttp;
  xmlHttp=new XMLHttpRequest();
  var x,y;
  x=document.getElementById("input_x").value;
  y=document.getElementById("input_y").value;
  xmlHttp.open("GET","multiply.php?x="+x+"&y="+y,true);

  xmlHttp.onreadystatechange=function() {
  if(xmlHttp.readyState==4){
    var pElement=document.getElementById("msg");
     pElement.innerHTML=xmlHttp.responseText;
     }
   }
  xmlHttp.send(null);
}
</script>
x:<input id="input_x" type="text"/ ><br>
y:<input id="input_y" type="text"/>  
<a href="javascript:multiply();">Multiply</a>
<br>
------------------------</br>
Result: 
<p id="msg"></p>

</body>
</html>


Note that x and y values are sent in url. You can also send them in send function, provided that your receiving page asumes they are form posts.

multiply-post.php

<html>
<body>
<? echo $_POST["x"]*$_POST["y"]?>
</body>
</html>

multiply-ajax.php

<html>
<body>
<script>
function multiply (){
  var xmlHttp;
  xmlHttp=new XMLHttpRequest();
  var x,y;
  x=document.getElementById("input_x").value;
  y=document.getElementById("input_y").value;
 var req="x="+x+"&y="+y;

  xmlHttp.open("POST","multiply.php",true);

  xmlHttp.onreadystatechange=function() {
  if(xmlHttp.readyState==4){
    var pElement=document.getElementById("msg");
     pElement.innerHTML=xmlHttp.responseText;
     }
   }

  xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xmlHttp.setRequestHeader("Content-length", req.length);
  xmlHttp.setRequestHeader("Connection", "close");
  xmlHttp.send(req);

}
</script>
x:<input id="input_x" type="text"/ ><br>
y:<input id="input_y" type="text"/>  
<a href="javascript:multiply();">Multiply</a>
<br>
------------------------</br>
Result: 
<p id="msg"></p>

</body>
</html>


[edit] Teams for this module

Team 0: Katherine T. Maschmeyer, Micah Scott Herstand. Please use zoo.cse.wustl.edu

Team 1: Adam Glenn Berger, Mark Avram Lilien. Please use zoo.cse.wustl.edu

Team 2: Daniel Everett Harter, Garrett F Eardley. Please use zoo.cse.wustl.edu

Team 3: Timothy Felix Trinidad, Jeremy Wayne Williams. Please use zoo.cse.wustl.edu

Team 4: Thomas Jerry Moore, Aaron Edward Jacobs. Please use zoo.cse.wustl.edu

Team 5: Zachary Robert Dwiel, Weston Joseph Haught. Please use zoo.cse.wustl.edu

Team 6: Richard Zack Speyer, Ryan Allen Johns. Please use zoo.cse.wustl.edu

Team 7: Lauren Miranda Jackson, Justin Alante McClain. Please use oz.cse.wustl.edu

Team 8: David Kaminsky, Simon Tam. Please use oz.cse.wustl.edu

Team 9: Mamta Jaikumar Datwani, James Leslie Grady. Please use oz.cse.wustl.edu

Team 10: Helena Marie Wotring, Scott Zachary Bressler. Please use oz.cse.wustl.edu

Team 11: Gurnish Sahni, Douglas James Hyde. Please use oz.cse.wustl.edu

Team 12: Daniel Edward Brewster, Jeremy Neil Friedman. Please use oz.cse.wustl.edu

Team 13: Alan Jonathan Lundeen, David Cassey Schainker, Jeffery Tyrone Nelson. Please use oz.cse.wustl.edu

Team 14: Steven D Broner. Please use oz.cse.wustl.edu

Note that team 13 has three students and team 14 has one.

Personal tools