AJAX can be used for interactive communication with an XML file.
AJAX XML example
The following example will demonstrate how a web page can fetch information from an XML file with AJAX technology.
Example explained – The HTML page
The HTML page contains a link to an external JavaScript, an HTML form, and a div element:
| <html> <head> <script type="text/javascript" src="selectcd.js"></script> </head> <body> <form> <div id="txtHint"><b>CD info will be listed here…</b></div> </body> |
As you can see it is just a simple HTML formĀ with a simple drop down box called "cds".
The <div> below the form will be used as a placeholder for info retrieved from the web server.
When the user selects data, a function called "showCD" is executed. The execution of the function is triggered by the "onchange" event. In other words: Each time the user change the value in the drop down box, the function showCD is called.
Example explained – The JavaScript code
This is the JavaScript code stored in the file "selectcd.js":
| var xmlhttp
function showCD(str) function stateChanged() function GetXmlHttpObject() |
The stateChanged() and GetXmlHttpObject functions are the same as in the PHP AJAX Suggest chapter, you can go to there for an explanation of those.
The showCD() Function
When a CD in the drop-down box is selected, the showCD() function executes the following:
- Calls the GetXmlHttpObject() function to create an XMLHTTP object
- Defines an URL (filename) to send to the server
- Adds a parameter (q) to the URL with the content of the drop-down box
- Adds a random number to prevent the server from using a cached file
- Each time the readyState property changes, the stateChanged() function will be executed
- Opens the XMLHTTP object with the given URL
- Sends an HTTP request to the server
Example explained – The PHP Page
The server paged called by the JavaScript, is a PHP file called "getcd.php".
The PHP script loads an XML document, "cd_catalog.xml", runs a query against the XML file, and returns the result as HTML:
| <?php $q=$_GET["q"]; $xmlDoc = new DOMDocument(); $x=$xmlDoc->getElementsByTagName(‘ARTIST’); for ($i=0; $i<=$x->length-1; $i++) $cd=($y->childNodes); for ($i=0;$i<$cd->length;$i++) |
When the CD query is sent from the JavaScript to the PHP page, the following happens:
- PHP creates an XML DOM object
- Find all <artist> elements that matches the name sent from the JavaScript
- Output the album information (send to the "txtHint" placeholder)
