w3schools    w3Schools
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 XML Example

Previous Next

AJAX can be used for interactive communication with an XML file.


AJAX XML Example

In the AJAX example below we will demonstrate how a web page can fetch information from an XML file using AJAX technology.


Select a CD in the Box Below

Select a CD:
CD info will be listed here.

This example consists of four pages:

  • a simple HTML form
  • an XML file
  • a JavaScript
  • a PHP page

The HTML Form

The example above contains a simple HTML form and a link to a JavaScript:

<html>
<head>
<script src="selectcd.js"></script>
</head>
<body>
<form> 
Select a CD:
<select name="cds" onchange="showCD(this.value)">
<option value="Bob Dylan">Bob Dylan</option>
<option value="Bee Gees">Bee Gees</option>
<option value="Cat Stevens">Cat Stevens</option>
</select>
</form>
<p>
<div id="txtHint"><b>CD info will be listed here.</b></div>
</p>
</body>
</html>

Example Explained

As you can see it is just a simple HTML form  with a simple drop down box called "cds".

The paragraph below the form contains a div called "txtHint". The div is 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 changes the value in the drop down box, the function showCD is called.


The XML File

The XML file is "cd_catalog.xml". This document contains a CD collection.


The JavaScript

This is the JavaScript code stored in the file "selectcd.js":

var xmlHttp;

function showCD(str)
{ 
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
 {
 alert ("Browser does not support HTTP Request");
 return;
 } 
var url="getcd.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("txtHint").innerHTML=xmlHttp.responseText;
 } 
}
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 stateChanged() and GetXmlHttpObject functions are the same as in the last chapter, you can go to the previous page for an explanation of those

The showCD() Function

If an item in the drop down box is selected the function executes the following:

  1. Calls on the GetXmlHttpObject function to create an XMLHTTP object
  2. Defines the url (filename) to send to the server
  3. Adds a parameter (q) to the url with the content of the input field
  4. Adds a random number to prevent the server from using a cached file
  5. Call stateChanged when a change is triggered
  6. Opens the XMLHTTP object with the given url.
  7. Sends an HTTP request to the server

The PHP Page

The server paged called by the JavaScript, is a simple PHP file called "getcd.php".

The page is written in PHP using the XML DOM to load the XML document "cd_catalog.xml".

The code runs a query against the XML file and returns the result as HTML:

<?php
$q=$_GET["q"];
$xmlDoc = new DOMDocument();
$xmlDoc->load("cd_catalog.xml");
$x=$xmlDoc->getElementsByTagName('ARTIST');
for ($i=0; $i<=$x->length-1; $i++)
{
//Process only element nodes
if ($x->item($i)->nodeType==1)
  {
  if ($x->item($i)->childNodes->item(0)->nodeValue == $q)
    { 
    $y=($x->item($i)->parentNode);
    }
  }
}
$cd=($y->childNodes);
for ($i=0;$i<$cd->length;$i++)
{ 
//Process only element nodes
if ($cd->item($i)->nodeType==1)
  { 
  echo($cd->item($i)->nodeName);
  echo(": ");
  echo($cd->item($i)->childNodes->item(0)->nodeValue);
  echo("<br />");
  } 
}
?>

Example Explained

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

  1. PHP creates an XML DOM object of the "cd_catalog.xml" file
  2. All  "artist" elements (nodetypes = 1) are looped through to find a name matching the one sent from the JavaScript.
  3. The CD containing the correct artist is found
  4. The album information is output and sent to the "txtHint" placeholder

Previous Next


The tools you need to build your web project!

Instant Demo

Ektron CMS400.NET Version 7.6 delivers all of the flexibility and features you need to deploy the Web site you want, quickly and efficiently.

learn more...

 

 

 

6 ways to take your site to the next level with Ektron:

Social Networking Create site stickiness through social networking. Keep it personal, relevant and interactive and they'll come back for more.
Open API Keep it open. Your site needs to be ready and able to connect to outside services. Ektron's open API gives you maximum flexibility.
Document Management Streamline content and document management. Users need to quickly and intuitively find and add information.
Content Authors Empower your content authors. Reduce IT bottlenecks by allowing business users to create and edit Web content and forms.
Taxonomy Climb to the top of search rankings. SEO tools, URL aliasing and eCommerce for your digital marketing strategy
Web 2.0 Tools Add powerful Web 2.0 tools like blogs, wikis, forums, geo-mapping, rating systems and RSS feeds easily.
See why there are 20,000+ Ektron integrations worldwide.
Request an INSTANT DEMO or download a FREE TRIAL today.

 
WEB HOSTING
dotnetbutton
Dynamic button image generation
$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 HOME or Top of Page Validate   Validate   W3C-WAI level A conformance icon Printer Friendly  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.