As a web developer, you may have asked yourself whether it was possible to update information from the server without having to refresh a page or use a heavy applet such as Flash or Java. As you may have seen with weather information widgets and stock tickers, not only is it possible--it's relatively easy when the solution is AJAX.
//This is the globally accessible xmlHttpRequest variable.
//If this is IE, or uses ActiveX, create an ActiveXObject
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
else if (window.XMLHttpRequest)
//Otherwise create an XMLHttpRequest object
xmlHttp = new XMLHttpRequest();
Now that you have your xmlHttp object, and its initialization function, let's create a basic request string to send to the server. For context, let's imagine that we're polling the server for weather information using a city name and its respective zip code.
var querystring = "myserver.com/myfolder/myfile.php?city=Beverly%20Hills&zip=90210"; //Create a simple query string, Ill
//leave more complicated examples
//as an exercise for later.
We now have an xmlHttp object and a query for our server, let's now send the request using the GET method and setup a callback function to handle the response from the server.
// Set up our xmlHttp object
var query = createQueryString();
//create our query string
xmlHttp.onreadystatechange = handleStateChange;
//set our callback handler
xmlHttp.open("GET", querystring, true);
//open the connection
//Send our query to the server
//This is a callback function that gets notified
//when server updates its response info.
if (xmlHttp.readyState == 4)
//a readyState of 4 means the response has been received
if (xmlHttp.status == 200)
//a status of 200 means everything went smoothly
//with the server (not necessarily the script though!)
//call the function that parses and handles our results
//The most simple method of handling the output.