w3schools
  
HOME HTML CSS XML JAVASCRIPT ASP PHP SQL MORE...   References Examples Forum About
BEST WEB HOSTING JustHosts

PHP Basic

PHP HOME
PHP Intro
PHP Install
PHP Syntax
PHP Variables
PHP String
PHP Operators
PHP If...Else
PHP Switch
PHP Arrays
PHP While Loops
PHP For Loops
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

PHP Example - responseXML

« Previous Next Chapter »

responseText returns the HTTP response as a string.

responseXML returns the response as XML.


AJAX ResponseXML example

The ResponseXML property returns an XML document object, which can be examined and parsed using the DOM.

The following example will demonstrate how a web page can fetch information from a database with AJAX technology. The selected data from the database will this time be converted to an XML document, and then we will use the DOM to extract the values to be displayed.

This example might look equal to the "PHP AJAX and MySQL" example in the previous chapter. However, there is a big difference: this time we get the data from the PHP page as XML, with the responseXML function.

Receiving the response as an XML document allows us to update this page several places, instead of just receiving an HTML output, and displaying it.

In this example we will update several <span> elements with the information we receive from the database.

Select a User:

 


Example explained - The MySQL Database

The database table we use 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


Example explained - The HTML page

The HTML page contains a link to an external JavaScript, an HTML form, and several <span> elements:

<html>
<head>
<script type="text/javascript" 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>
  • The HTML form contains a drop-down box called "users", with id and names from the database table, as options
  • The <span> elements are placeholders for the values we will receive
  • When a user is selected, a function called "showUser()" is executed (triggered by the "onchange" event)

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


Example explained - The JavaScript code

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)
  {
  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()
{
if (window.XMLHttpRequest)
  {
  // code for IE7+, Firefox, Chrome, Opera, Safari
  return new XMLHttpRequest();
  }
if (window.ActiveXObject)
  {
  // code for IE6, IE5
  return new ActiveXObject("Microsoft.XMLHTTP");
  }
return null;
}

The showUser() and GetXmlHttpObject functions are the same as in the PHP AJAX and MySQL chapter, you can go to there for an explanation of those.

The stateChanged() Function

When an option in the drop-down box is selected, the function executes the following:

  1. Sets xmlDoc variable as an XML document, using the responseXML function
  2. Retrieves data from the XML document, and place it in the correct <span> element

Example explained - The PHP Page

The PHP page called by the JavaScript, is called "responsexml.php".

The PHP script runs an SQL query against a MySQL database, and returns the result an XML document:

<?php
$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);
?>

When the query is sent from the JavaScript to the PHP page, the following happens:

  1. Set the $q variable to the data sent in the q parameter
  2. Open a connection to a MySQL server
  3. The "user" with the specified id is found
  4. The data is outputted as an XML document

« Previous Next Chapter »


Make your web applications look like a million bucks

FusionCharts   

Most web applications today use boring methods to present data to their viewers using grids or simple HTML tables. FusionCharts induces "life" into the web applications by converting monotonous data into lively charts, gauges & maps.

FusionCharts works with all technologies like ASP, ASP.NET, PHP, ColdFusion, Ruby on Rails, JSP, HTML pages etc. and connects to any database to render animated & interactive charts. It takes less than 15 minutes and no expertise whatsoever to build your first chart and just a glance of it to captivate your audience. This fact is endorsed by our 12,000 customers and 150,000 users which include a majority of the Fortune 500 companies. And yeah, your applications could look like a million bucks by spending just $69.

So go ahead, download your copy of FusionCharts and start "wow-ing" your customers now!



W3Schools Certification

W3Schools' Online Certification Program

The perfect solution for professionals who need to balance work, family, and career building.

More than 4000 certificates already issued!

The HTML Certificate documents your knowledge of HTML, XHTML, and CSS.

The JavaScript Certificate documents your knowledge of JavaScript and HTML DOM.

The XML Certificate documents your knowledge of XML, XML DOM and XSLT.

The ASP Certificate documents your knowledge of ASP, SQL, and ADO.

The PHP Certificate documents your knowledge of PHP and SQL (MySQL).

WEB HOSTING
Best Web Hosting
PHP MySQL Hosting
Top 10 Web Hosting
UK Reseller Hosting
Web Hosting
FREE Web Hosting
Top Web Hosting
Windows Hosting
WEB BUILDING
XML Editor – Free Trial!
FREE Flash Website
FREE Web Templates
FLIGHT TICKETS
Find the cheapest flight
to any destination now!
EDUCATION
US Web Design Schools
HTML Certification
JavaScript Certification
XML Certification
PHP Certification
ASP Certification
STATISTICS
Browser Statistics
Browser OS
Browser Display