Latest web development tutorials

PHP AJAX and XML instance

AJAX can be used to communicate interactively with the XML file.

AJAX XML instance

The following examples will demonstrate how a web page via AJAX reading information from an XML file:


CD info will be listed here...

Examples explain - HTML page

When a user in the above drop-down list to select a Double CD, it performs named "showCD ()" function. This function by the "onchange" event is triggered:

function showCD(str)
	if (str=="")
	if (window.XMLHttpRequest)
		// IE7+, Firefox, Chrome, Opera, Safari 浏览器执行
		xmlhttp=new XMLHttpRequest();
		// IE6, IE5 浏览器执行
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		if (xmlhttp.readyState==4 && xmlhttp.status==200)

Select a CD:
<select name="cds" onchange="showCD(this.value)">
<option value="">Select a CD:</option>
<option value="Bob Dylan">Bob Dylan</option>
<option value="Bonnie Tyler">Bonnie Tyler</option>
<option value="Dolly Parton">Dolly Parton</option>
<div id="txtHint"><b>CD info will be listed here...</b></div>


showCD () function performs the following steps:

  • Check whether the CD is selected
  • Create XMLHttpRequest object
  • Create function when the server is ready to perform the response
  • File on the server to send requests
  • Please note added to the end of the URL parameter (q) (contains the contents of the drop-down list)

PHP File

The above servers through JavaScript calling this page is called "getcd.php" PHP file.

PHP script to load an XML document, " cd_catalog.xml ", to run queries against XML file and returns the result as HTML:


$xmlDoc = new DOMDocument();


for ($i=0; $i<=$x->length-1; $i++)
	// 处理元素节点
	if ($x->item($i)->nodeType==1)
		if ($x->item($i)->childNodes->item(0)->nodeValue == $q)


for ($i=0;$i<$cd->length;$i++)
	// 处理元素节点
	if ($cd->item($i)->nodeType==1)
		echo("<b>" . $cd->item($i)->nodeName . ":</b> ");

When the CD query is sent from JavaScript to PHP page will occur:

  1. PHP create XML DOM object
  2. Find all <artist> element with JavaScript preached data matching names
  3. Output album information, and sends back "txtHint" placeholder