gregdoolittle.com

Ace + Jack = Ajax (Chapter 2)

January 21st, 2007

Head Rush Ajax Chapter 2 covers onreadystatechange, readystate, status, responseText, server errors, callback functions, a simple IE/Opera hack…

onreadystatechange is a property of the Ajax request object. basically, you use this property to tell your browser what to do once the Ajax object has received its request from the server. In the following example, the browser will run updatePage() after the server has finished executing and delivering the request.

request.onreadystatechange = updatePage;


Notice that updatePage() is a function, yet there are no parentheses when we assign the function to the property. When updatePage() is used in this way, it’s called a “callback function”.

readystate is another property of the Ajax request object. The readystate is a number from 0 to 4 and represents a the current state of the request: 0. uninitialized, 1. initialized (request has been made received), 2. server is locating the file or process, 3. server is executing the script or process, 4. the server has finished and the request object is ready.

status is the condition of a request. A status value of 200 represents a successful execution of a script. 404 is an error message, and means the file was not found. 403 is another error message, meaning that access to the desired file or process has been denied. There is a complete list of the HTTP error codes available here.

responseText is the text returned from a PHP script sent through a request object. If we run the script “example.php?id=00001″, and the content of the output of the script is “Homer Simpson”, then responseText will store the string “Homer Simpson”.

var newText = request.responseText;

Finally, a simple IE / Opera hack is necessary because these browsers try to cache entire webpages. If you’re accessing a script that should return a new value each time it’s called, you’ll have to go a step further for these browsers. You can append an otherwise superfluous variable to make the browser go get the new data each time the script is called.
By adding a random modifier we can trick the browser into thinking it is accessing a new URL:

var url = "getUpdatedBoardSales-ajax.php?date="+ escape(Date());
request.open("GET", url, true);

The browser will then go look for the following unique URL:

getUpdatedBoardSales-ajax.php?date=Sun%20Jan%2021%20...


Remember, this is only necessary when the browser is accessing a script that gets updated every time the script is called. There are several instances where having a cached page will improve the agility of the script.

When I finish the homework scripts from this chapter I will post a link to them in this entry.

Powered by WordPress