PHP and AJAX responseXML Example
- Previous Page AJAX Database
- Next Page AJAX Live Search
AJAX can be used to return database information in XML format.
AJAX Database to XML Example (Test Note: The functionality of this instance is not implemented)
In the following AJAX example, we will demonstrate how a webpage reads information from a MySQL database, converts the data into an XML document, and uses this document to display information in different places.
This example is very similar to the "PHP AJAX Database" example in the previous section, but there is a significant difference: in this example, we get data in XML format by using the responseXML function from the PHP page.
Receiving an XML document as a response allows us to update multiple locations on the page, not just receive a PHP output and display it.
In this example, we will use information received from the database to update multiple <span> elements.
Select a name from the drop-down list
This column consists of four elements:
- MySQL Database
- Simple HTML Form
- JavaScript
- PHP page
Database
The database used in this example looks something like this:
id | FirstName | LastName | Age | Hometown | Job |
---|---|---|---|---|---|
1 | Peter | Griffin | 41 | Quahog | Brewery |
2 | Lois | Griffin | 40 | Newport | Piano Teacher |
3 | Joseph | Swanson | 39 | Quahog | Police Officer |
4 | Glenn | Quagmire | 41 | Quahog | Pilot |
HTML Form
The above example includes a simple HTML form and a link to JavaScript:
<html> <head> <script src="responsexml.js"></script> </head> <body> <form> Select a User: <select name="users" onchange="showUser(this.value)"> <option value="1">Peter Griffin</option> <option value="2">Lois Griffin</option> <option value="3">Glenn Quagmire</option> <option value="4">Joseph Swanson</option> </select> </form> <h2> <span id="firstname"></span> <span id="lastname"></span> </h2> <span id="job"></span> <div style="text-align: right"> <span id="age_text"></span> <span id="age"></span> <span id="hometown_text"></span> <span id="hometown"></span> </div> </body> </html>
Example Explanation - HTML Form
- The HTML form is a dropdown list with a name attribute value of "users", and the option values correspond to the database's id field
- There are several <span> elements below the form, which are used as placeholders for the different values we receive
- When the user selects a specific option, the function "showUser()" will be executed. The execution of this function is triggered by the "onchange" event
In other words, every time the user changes the value in the dropdown list, the function showUser() will be executed and the result will be output in the specified <span> element.
JavaScript
This is the JavaScript code stored in the file "responsexml.js":
var xmlHttp function showUser(str) { xmlHttp = GetXmlHttpObject() if (xmlHttp==null) { alert ("Browser does not support HTTP Request") return } var url="responsexml.php" url=url+"?q="+str url=url+"&sid="+Math.random() xmlHttp.onreadystatechange=stateChanged xmlHttp.open("GET",url,true) xmlHttp.send(null) } function stateChanged() { if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") { xmlDoc=xmlHttp.responseXML; document.getElementById("firstname").innerHTML= xmlDoc.getElementsByTagName("firstname")[0].childNodes[0].nodeValue; document.getElementById("lastname").innerHTML= xmlDoc.getElementsByTagName("lastname")[0].childNodes[0].nodeValue; document.getElementById("job").innerHTML= xmlDoc.getElementsByTagName("job")[0].childNodes[0].nodeValue; document.getElementById("age_text").innerHTML="Age: "; document.getElementById("age").innerHTML= xmlDoc.getElementsByTagName("age")[0].childNodes[0].nodeValue; document.getElementById("hometown_text").innerHTML="<br/>From: "; document.getElementById("hometown").innerHTML= nodeValue of the first child node of the element "hometown" in xmlDoc } } function GetXmlHttpObject() { var objXMLHttp=null if (window.XMLHttpRequest) { objXMLHttp=new XMLHttpRequest() } else if (window.ActiveXObject) { objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP") } return objXMLHttp }
Example Explanation:
showUser() and GetXmlHttpObject function with PHP and AJAX MySQL Database Example The examples in this section are the same. You can refer to the relevant explanations within.
stateChanged() function
If an item in the dropdown list is selected, this function is executed:
- Using the responseXML function, define the "xmlDoc" variable as an XML document
- Retrieve data from this XML document and place them in the correct "span" elements
PHP page
This server-side page, called "responsexml.php", is a simple PHP file that is called by JavaScript.
This page is written in PHP and uses the MySQL database.
The code will run a SQL query against the database and return the results as an XML document:
<?php header('Content-Type: text/xml'); header("Cache-Control: no-cache, must-revalidate"); //A date in the past header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); $q=$_GET["q"]; $con = mysql_connect('localhost', 'peter', 'abc123'); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("ajax_demo", $con); $sql="SELECT * FROM user WHERE id = ":.$q.":"; $result = mysql_query($sql); echo '<?xml version="1.0" encoding="ISO-8859-1"?> <person>' while($row = mysql_fetch_array($result)) { echo "<firstname>" . $row['FirstName'] . "</firstname>"; echo "<lastname>" . $row['LastName'] . "</lastname>"; echo "<age>" . $row['Age'] . "</age>"; echo "<hometown>" . $row['Hometown'] . "</hometown>"; echo "<job>" . $row['Job'] . "</job>"; } echo "</person>"; mysql_close($con); ?>
Example Explanation:
When the query is sent from JavaScript to the PHP page, the following occurs:
- The content-type of the PHP document is set to "text/xml"
- PHP document is set to "no-cache" to prevent caching
- Set the $q variable with data sent from an HTML page
- PHP opens a connection to the MySQL server
- Find the "user" with the specified id
- Output data in XML document format
- Previous Page AJAX Database
- Next Page AJAX Live Search