OK. I've been wanting to write an article about the myriad wonders of Ajax almost since I first found out about it. Ajax is a very powerful and flexible technology (almost as good as XML ), and I love raving about it. I've just found some time to write this article; I'm currently rather depressed with some work I've been doing for the past 8 hours, so I thought now was as best a time as any to sit down and spout.
So, on to the actual code.
The implementation of Ajax is rather simple - all the data is transferred using XML packets:
- It sets an "onreadystatechange" function to catch the response, and then exits
- The "onreadystatechange" function catches the response from the server, and parses the XML
- It then dynamically calls the respective function to deal with the actual data received
//Branch for decent browsers' XMLHttpRequest object
//Branch for IE
This function is called on the client-side when you want to initiate an Ajax transaction. It requests a document from the server, sets a function to catch the response, then disappears. It uses different methods of communication for different browsers (Gecko / MSIE), but the end result is still the same.
//If req is 'complete'
//If status is 'OK'
//Process the result
alert("There was a problem retrieving the XML data:n"+req.statusText);
This function receives the XML data packet sent by the server, extracts the useful data, and calls the right function to handle said data. Note that the XML handling is all done through the DOM. No IE-only old methods for Ajax.
This is all fine and well...but without the XML data format, everyone's a bit stuck:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
There are three main points of interest here:
- The "result" tag: it contains the actual data to be used
This data has to be sent with a certain MIME type ("text/xml"). The following PHP code will achieve that:
//Deal with the response
window.alert("Received message: "+response);
//Make the query!
This function is exceedingly simple, but it manages to deal with the sending and handling of the data.
Coupled with a PHP script ("sample.php"):
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
echo 'Hello world!';
echo 'Goodbye world.';
echo 'Unknown message_number.';
That should work, and give you a nice little spiced up "Hello world" script - using Ajax
To make things a little friendlier for the user, you could use DOM manipulation to place results in the page dynamically.
For some neat (even if I do say so myself!) examples of Ajax in action, see Helios