Ajax (Asynchronous Javascript and XML) provides a very neat way for a web page that's displayed on a browser to interact with a web server and replace just
part of the page content without the need to reload the whole HTML document or Frame.
It works like this:
1. The original document called up from the server include Javascript which
diverts changes to form elements to a local Javascript function
2. The local Javascript function creates an appropriate XMLHttpRequest object, which it sends off to the server.
3. When the response from the server comes back, an event handler at the browser (more Javascript) reads it, and uses it to amend the HTML of the web page.
Ajax isn't really a technology in its own right - rather, it's the combination of a number of other technologies which you'll need to get to grips with to understand how it works. In spare moments over the last 10 days, I've been reading in to and experimenting with Ajax, and I've found that all the examples are over complex as starters - so I've written my own. The complete example is published:
HERE for the web page (.html with Javascript added) sent to the browser and
HERE for the code the runs on the server to provide the web service.
You can try it out
here
I have tried - SO hard - to keep this example simple, and complete in just the two files of source I have provided links to above. Here are explanations of some of the more critical bits:
Firstly, the code for the select option menu which triggers the Javascript:
<select onChange="aboutlang(this)">
<option value="None">------</option>
<option value="Perl">Perl</option>
<option value="PHP">PHP</option>
<option value="Python">Python</option>
</select>
Here is some of the Javascript that it triggers (with extra comments added):
function aboutlang(current) {
// Get the value that has just been selected
var lang = current.options[current.selectedIndex].value;
// Make up a request to send to the server
var rqo = new XMLHttpRequest();
// Add in the value that has been entered to the URL
var qs = encodeURIComponent(lang);
var qry = "ajaxcode.php?towhich=" + qs;
// Send the request, saying you want to wait for it to complete
// before carrying on
rqo.open('GET',qry,false);
rqo.send(null);
// Take the entire response, and replace the element that's called
// "result" in your HTML with whatever you got back
document.getElementById("result").innerHTML = rqo.responseText;
// Tell the browser that it has no further actions
return false;
}
The PHP - to run on the server - takes the parameter that's passed in to it and generates a snippet of HTML (in this example):
<?php
$responses = array(
"Perl" => "Perl was written by Larry Wall",
"PHP" => "Rasmus Lerdorf wrote PHP",
"Python" => "From Guido van Rossum came Python");
$send = $responses[$_REQUEST[towhich]];
if ($send == "") {
$send = " --- No information available --- ";
}
$send = "Data retrieved from server at ".date("H:i:s").
" server time<br /><br />"."<b>$send</b>";
print ($send);
?>
Illustration - the page as initially loaded
Technically, my example isn't really Ajax - it's not asynchronous in that it waits for the server before completing the function at the browser. It's a little more complex, requiring a further function and more logic to handle the events / callbacks of going asynchronous, so that will be lesson 2 rather than lesson one. And also, you could point out to me that I'm not actually sending XML back from the PHP script, but rather just plain ole HTML. Yes - again, that can wait for lesson 2. The example above works
on compliant browsers - lesson 3 will tell you how to 'fix' your Javascript to recognise browsers that behave in a somewhat different manner ... for the meantime, I'm going to use the dreadful works "this example is best viewed on Firefox ;-) "
Illustration - the page as amended after a server request
Using Ajax (with PHP on the server side) is covered on our
PHP techniques Workshop - a two day course that runs every 8 to 12 weeks, and helps you make the very best of your PHP. If you're interested in learning other aspect of Javascript, please email me
graham@wellho.net.
See
[here] for the second lesson in this series, where I explain what "Asyncronous" means, why you'll want to use it, and how to implement it in Ajax.
(written 2008-09-27, updated 2008-09-28)
Associated topics are indexed as below, or enter http://melksh.am/nnnn for individual articles
W602 - Web and Intranet - Client Side Technologies [411] Javascript examples (some PHP and MySQL too) - (2005-08-13)
[522] Javascript events - a good example - (2005-12-09)
[1322] Flash - is it available to your web page? - (2007-08-26)
[1681] Adding a button to a web page to print the page - (2008-06-18)
[1749] Using server side and client side programming together - (2008-08-11)
[1813] Ajax - going Asyncronous and what it means - (2008-09-28)
[1814] Javascript/HTML example, dynamic server monitor - (2008-09-28)
[2390] Dynamic / changing images on your web page - (2009-09-01)
[2628] An example of an injection attack using Javascript - (2010-02-08)
[3128] How does your browser find out about itself? - (2011-01-11)
[4277] Sending a message to the server and changing text on a page when a button is pressed - (2014-05-23)
[4310] Problem ... I want to print a series of numbered forms - (2014-10-05)
W510 - Web and Intranet - Executable ContentH307 - PHP - Web2 and caching [1633] Changing a screen saver from a web page (PHP, Perl, OSX) - (2008-05-06)
[1647] Exchange Rates - PHP with your prices in your users currency - (2008-05-19)
[1733] memcached - overview, installation, example of use in PHP - (2008-08-02)
[1926] Flash (client) to PHP (server) - example - (2008-12-06)
[1995] Automated server heartbeat and health check - (2009-01-16)
[2196] New Example - cacheing results in PHP for faster loading - (2009-05-24)
[2321] Uploading and Downloading files - changing names (Perl and PHP) - (2009-08-04)
[2545] Scraping content for your own page via PHP - (2009-12-21)
[3029] PHP data sources - other web servers, large data flows, and the client (browser) - (2010-11-04)
[3094] Setting your user_agent in PHP - telling back servers who you are - (2010-12-18)
[3186] How to add a customised twitter feed to your site - (2011-02-27)
[3458] On this day ... one PHP script with three uses - (2011-09-26)
[3955] Building up from a small PHP setup to an enterprise one - (2012-12-16)
[3999] Handling failures / absences of your backend server nicely - (2013-02-08)
[4055] Using web services to access you data - JSON and RESTful services - (2013-03-29)
[4075] Further recent PHP examples - (2013-04-28)
[4106] Web server efficiency - saving repetition through caches - (2013-05-30)
[4136] How do I post automatically from a PHP script to my Twitter account? - (2013-07-10)
[4627] Caching results in an object for efficiency - avoiding re-calculation - (2016-01-20)
Some other Articles
Holt on holtHotel Guest SurveysStarting Ajax - easy example of browser calling up server dataAlternative URLs using % symbol encodingMiddle aged subsidise young and oldComing home tonightWe love children ... but our hotel is not going to be their sceneA sad town in the sunlight