PHP and AJAX responseXML Example
AJAX can be used to return database information as XML.
AJAX Database as XML Example
In the AJAX example below we will demonstrate how a web page can fetch information from a MySQL database, convert it to an XML document, and use it to display information in several different places.This example my seem a lot like the "PHP AJAX Database" example in the last chapter, however there is a big difference: in this example we get the data from the PHP page as XML using the responseXML function.
Receiving the response as an XML document allows us to update this page several places, instead of just receiving a PHP output and displaying it.
In this example we will update several <span> elements with the information we receive from the database.
Select a Name in the Box Below
- a MySQL database
- a simple HTML form
- a JavaScript
- a PHP page
The Database
The database we will be using in this example looks 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 |
The HTML Form
The example above contains a simple HTML form and a link to a 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 Explained - The HTML Form
- The HTML form is a drop down box called "users" with names and the "id" from the database as option values.
- Below the form there are several different <span> elements which are used to as placeholders for the different values we will retrive.
- When the user selects data, a function called "showUser()" is executed. The execution of the function is triggered by the "onchange" event.
The 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= xmlDoc.getElementsByTagName("hometown")[0].childNodes[0].nodeValue; } } function GetXmlHttpObject() { var objXMLHttp=null; if (window.XMLHttpRequest) { objXMLHttp=new XMLHttpRequest(); } else if (window.ActiveXObject) { objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP"); } return objXMLHttp; } |
Example Explained
The showUser() and GetXmlHttpObject functions are the same as in the PHP AJAX Database chapter, you can go to there for an explanation of those.The stateChanged() Function
If an item in the drop down box is selected the function executes the following:
1. Defines the "xmlDoc" variable as an xml document using the responseXML function
2. Retrieves data from the xml documents and places them in the correct <span> elements
The PHP Page
The server page called by the JavaScript, is a simple PHP file called "responsexml.php".The page is written in PHP and uses a MySQL databse.
The code runs a SQL query against a database and returns the result 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 Explained
When the query is sent from the JavaScript to the PHP page the following happens:1. The content-type of the PHP document is set to be "text/xml"
2. The PHP document is set to "no-cache" to prevent caching
3. The $q variable is set to be the data sent from the html page
4. PHP opens a connection to a MySQL server
5. The "user" with the specified id is found
6. The data is outputted as an xml document
PHP and AJAX Live Search
AJAX can be used for a more user friendly and interactive search.
AJAX Live Search
In the AJAX example below we will demonstrate a live search, where the server gets search results while the user types.Live search has many benefits compared to traditional searching:
- Matching results are shown as you type
- Results narrow as you continue typing
- If results become too narrow, remove characters to see a broader result
Search for a W3Schools page in the Box Below
This example consists of four pages:- a simple HTML form
- a JavaScript
- a PHP page
- an XML document
The HTML Form
This is the HTML page. It contains a simple HTML form, style for the form and a link to a JavaScript:<html> <head> <script src="livesearch.js"></script> <style type="text/css"> #livesearch { margin:0px; width:194px; } #txt1 { margin:0px; } </style> </head> <body> <form> <input type="text" id="txt1" size="30" onkeyup="showResult(this.value)"> <div id="livesearch"></div> </form> </body> </html> |
Example Explained - The HTML Form
As you can see, the HTML page above contains a simple HTML form with an input field called "txt1".The form works like this:
1. An event is triggered when the user presses, and releases a key in the input field
2. When the event is triggered, a function called showResult() is executed.
3. Below the form is a <div> called "livesearch". This is used as a placeholder for the return data of the showResult() function.
The JavaScript
The JavaScript code is stored in "livesearch.js" and linked to the HTML document:var xmlHttp; function showResult(str) { if (str.length==0) { document.getElementById("livesearch"). innerHTML=""; document.getElementById("livesearch"). style.border="0px"; return; } xmlHttp=GetXmlHttpObject() if (xmlHttp==null) { alert ("Browser does not support HTTP Request"); return; } var url="livesearch.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") { document.getElementById("livesearch"). innerHTML=xmlHttp.responseText; document.getElementById("livesearch"). style.border="1px solid #A5ACB2"; } } function GetXmlHttpObject() { var xmlHttp=null; try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttp; } |
Example Explained
The GetXmlHttpObject function is the same as in the PHP AJAX Suggest chapter.The showResult() Function
This function executes every time a character is entered in the input field.
If there is no input in the text field (str.length == 0) the function sets the return field to empty and removes any border around it.
However, if there is any input in the text field the function executes the following:
1. Defines the url (filename) to send to the server
2. Adds a parameter (q) to the url with the content of the input field
3. Adds a random number to prevent the server from using a cached file
4. Calls on the GetXmlHttpObject function to create an XMLHTTP object, and tells the object to execute a function called stateChanged when a change is triggered
5. Opens the XMLHTTP object with the given url.
6. Sends an HTTP request to the server
The stateChanged() FunctionThis function executes every time the state of the XMLHTTP object changes.
When the state changes to 4 (or to "complete"), the content of the txtHint placeholder is filled with the response text, and a border is set around the return field.
The PHP Page
The server page called by the JavaScript code is a PHP file called "livesearch.php".The code in the "livesearch.php" checks the XML document "links.xml". This document contains titles and URL's of some pages on W3Schools.com.
The code searches the XML file for titles matching the search string and returns the result as HTML:
<?php $xmlDoc = new DOMDocument(); $xmlDoc->load("links.xml"); $x=$xmlDoc->getElementsByTagName('link'); //get the q parameter from URL $q=$_GET["q"]; //lookup all links from the xml file if length of q>0 if (strlen($q) > 0) { $hint=""; for($i=0; $i<($x->length); $i++) { $y=$x->item($i)->getElementsByTagName('title'); $z=$x->item($i)->getElementsByTagName('url'); if ($y->item(0)->nodeType==1) { //find a link matching the search text if (stristr($y->item(0)->childNodes->item(0)->nodeValue,$q)) { if ($hint=="") { $hint="<a href='" . $z->item(0)->childNodes->item(0)->nodeValue . "' target='_blank'>" . $y->item(0)->childNodes->item(0)->nodeValue . "</a>"; } else { $hint=$hint . "<br /><a href='" . $z->item(0)->childNodes->item(0)->nodeValue . "' target='_blank'>" . $y->item(0)->childNodes->item(0)->nodeValue . "</a>"; } } } } } // Set output to "no suggestion" if no hint were found // or to the correct values if ($hint == "") { $response="no suggestion"; } else { $response=$hint; } //output the response echo $response; ?> |
1. PHP creates an XML DOM object of the "links.xml" file
2. All "title" elements (nodetypes = 1) are looped through to find a name matching the one sent from the JavaScript
3. The link containing the correct title is found and set as the "$response" variable. If more than one match is found, all matches are added to the variable
4. If no matches are found the $response variable is set to "no suggestion"
5. The $result variable is output and sent to the "livesearch" placeholder
No comments:
Post a Comment