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.
//File is your php script called from the code
//first we need to get the variables from the GET request,
//just as you would with any form submission. I'm being lazy
//here and not really doing security checks
//so be careful before putting this, verbatim, on a live server
$city = $_GET['city'];
$zip = $_GET['zip'];
//Here is where you contact your database / filesystem for
//information (in this case, the weather for the city and state
//sent in). Load it into a variable, we'll call it $response;
$response = database/file info
Notice that we did not have to do anything special with the response text, just write it out to the page. The xmlHttp object reads the output of the page and uses it as its responseText.
That's it for our introduction to using AJAX and the PHP scripting language. Play around with it for a bit, take it for a test drive, and come back later when we use a POST request to actually update information in our database and send a more complex XML query and response!