PHP and AJAX responseXML Example

|  | Search W3Schools : |

HOME | HTML | CSS | XML | JAVASCRIPT | ASP | PHP | SQL | MORE... |  | References | Examples | Forum | About

ADVERTISEMENTS XML Certification Download XML editor Custom Programming |  |

Table of contents

PHP Basic
PHP HOME
PHP Intro
PHP Install
PHP Syntax
PHP Variables
PHP String
PHP Operators
PHP If...Else
PHP Switch
PHP Arrays
PHP Looping
PHP Functions
PHP Forms
PHP $_GET
PHP $_POST
PHP Advanced
PHP Date
PHP Include
PHP File
PHP File Upload
PHP Cookies
PHP Sessions
PHP E-mail
PHP Secure E-mail
PHP Error
PHP Exception
PHP Filter
PHP Database
MySQL Introduction
MySQL Connect
MySQL Create
MySQL Insert
MySQL Select
MySQL Where
MySQL Order By
MySQL Update
MySQL Delete
PHP ODBC
PHP XML
XML Expat Parser
XML DOM
XML SimpleXML
PHP and AJAX
AJAX Introduction
XMLHttpRequest
AJAX Suggest
AJAX XML
AJAX Database
AJAX responseXML
AJAX Live Search
AJAX RSS Reader
AJAX Poll
PHP Reference
PHP Array
PHP Calendar
PHP Date
PHP Directory
PHP Error
PHP Filesystem
PHP Filter
PHP FTP
PHP HTTP
PHP Libxml
PHP Mail
PHP Math
PHP Misc
PHP MySQL
PHP SimpleXML
PHP String
PHP XML
PHP Zip
PHP Quiz
PHP Quiz
PHP Exam

Selected Reading

Web Statistics
Web Glossary
Web Hosting
Web Quality
W3Schools Tutorials
W3Schools Forum
Helping W3Schools

# 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

Select a User:

##

This example consists of four elements:

- 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>
    &nbsp;<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.

In other words: Each time the user changes the value in the drop down box, the function showUser() is called and outputs the result in the specified <span> elements.

## 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

## Altova® XMLSpy® - The world's best-selling XML editor!

Whether you're new to XML or already an advanced user, the user-friendly views and powerful entry helpers, wizards, and debuggers in XMLSpy are designed to meet your XML and Web services development needs from start to finish.

- XML editor
- Graphical XML Schema / DTD editors
- XSLT 1.0/2.0 editor, debugger, profiler
- XQuery editor, debugger, profiler
- Support for Office Open XML (OOXML)
- Graphical WSDL editor & SOAP debugger
- Java, C#, C++ code generation
- And much more!

Download a fully functional free 30-day trial today!

WEB HOSTING
ASP.NET Shopping Cart
$15 Domain Name Registration Save $20 / year!
Buy UK Domain Names Register Domain Names
Cheap Domain Names Cheap Web Hosting
Best Web Hosting
PHP MySQL Hosting
Top 10 Web Hosting
UK Reseller Hosting
Web Hosting
FREE Web Hosting

WEB BUILDING
Website Templates Flash Templates Website Builder Internet Business Opportunity
Custom Programming
FREE Trial or Demo Web Content Manager Forms,Web Alerts,RSS
Download XML editor
FREE Flash Website
FREE Web Templates

EDUCATION
US Web Design Schools
HTML Certification
JavaScript Certification
XML Certification
PHP Certification
ASP Certification

HOME or Top of Page |  | Printer Friendly
W3Schools is for training only. We do not warrant the correctness of its content. The risk from using it lies entirely with the user. While using this site, you agree to have read and accepted our terms of use and privacy policy. Copyright 1999-2009 by Refsnes Data. All Rights Reserved.