Category Archives: ajax-with-php

Ajax with PHP

Ajax with PHP using responseXML

I’ll start off with a very basic technique of using Ajax with the responseXML (not responseText). responseXML basically means that the returned values is in an XML format. The other option would be to use responseText which in many cases would be the simplest method. But true Ajax uses XML (as the X in the name suggests).

OK, let’s dive right into some code.

First we want to create the XML HTTP Request Object (this is always required!)


var http = createRequestObject();

function createRequestObject() {  
	// find the correct xmlHTTP, works with IE, FF and Opera
	var xmlhttp;
	try {
  	xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
  }
  catch(e) {
    try {
    	xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    catch(e) {
    	xmlhttp=null;
    }
  }
  if(!xmlhttp&&typeof XMLHttpRequest!="undefined") {
  	xmlhttp=new XMLHttpRequest();
  }
	return  xmlhttp;
}
  

 

In the above we have used some error checking to see which method works with the users browser, Internet Explorer uses ActiveX while other browsers don’t. The try(), catch() functions are JavaScript’s way of finding errors and can be used to control any errors which might be returned to the users browser.

 

Now we’ll create the function which will handle sending the request to the Server Script (and pass values we require):


function sendRequest() {
	var name = document.getElementById("name").value;
	var email = document.getElementById("email").value;
	var rnd = Math.random();
	if(name.length >0 && email.length >0) {
		name=escape(name);
		email=escape(email);
	try{
    http.open("GET", "index_inc.php?name="+name+'&email='+email+'&rnd='+rnd, true);
    http.setRequestHeader('Content-Type',  "text/xml");
    http.onreadystatechange = handleResponse;
		http.send(null);
	}
	catch(e){
		// caught an error
		alert('Request send failed.');
	}
	finally{}
		// disable button until end of response
		document.getElementById('go').disabled = true;
		document.getElementById('go').value = "Hold On";
		// hide any previous returned values
		document.getElementById('returned_value').style.display="none";
	} else {
		alert("please complete both fields first");
	}
}
  

 

In the above snippet we first get the values we plan on sending to the Server, in this case ‘name’, ‘email’ and also a random number. The random number is used to help prevent browsers caching the any previous requests.

We then check the length of the values we will pass (we check that both name and email contain more than 1 character).
Using http.open we set the GET value as the method and the script path along with the values mentioned above.
The set the request header as content type text/xml then send the request to the server script. Notice we use ‘http.onreadystatechange = handleResponse;’ which tells the script to call the handleResponse function once the state has changed (we will get to this function next)

Once we try and catch any errors we do some cosmetic stuff like disable the Submit button and hide any previous returned values.

Handle the response from the server script:


function handleResponse() {
	try{
    if((http.readyState == 4)&&(http.status == 200)){
    	var response = http.responseXML.documentElement;
    	var n = response.getElementsByTagName('name')[0].firstChild.nodeValue;
    	var e = response.getElementsByTagName('email')[0].firstChild.nodeValue;
    	var r = response.getElementsByTagName('random')[0].firstChild.nodeValue;

    	// write out response
      document.getElementById("returned_value").innerHTML = 
      '
Returned: '+n+' ('+e+') Random: '+r; // re-enable the button document.getElementById('go').disabled = false; document.getElementById('go').value = "Submit"; document.getElementById('returned_value').style.display=""; } } catch(e){ // caught an error alert('Response failed.'); } finally{} }

In the above function we retrieve the response from the server script (the XML data) and get the values we want to use.

We then use the ‘document.getElementById(”returned_value”).innerHTML = ….etc’ to write the data to the browser.

Then enable the submit button… we’re done with the request and response now!!

OK, now to see the form used to get the values (name and email) from the user:



	
	

	
Ajax example (with responseXML)
   

Here is the XML which the server script returned to the browser:


< ?xml version="1.0"?>

  stuart
  stuartc1@hotmail.com
  0.98789

Important: Internet Explorer handles extra white space between XML elements fine, but other more strict browsers do not. So please check the format of your XML if you have problems. There are some JavaScript functions around which fix white space problems! In some cases though you can use the plain old responseText without the worry!

Take a look at this Ajax code in action
View the full source code.