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:
Here is the XML which the server script returned to the browser:
< ?xml version="1.0"?>
stuart
[email protected]
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.
Ooops – you may have noticed all the comments are gone. Well this is due to me having to downgrade the wordpress software. Version 2.0.1 was proving a bit of a nightmare for me, so I was forced to install an earlier, more stable version.
Please feel free to post you comments again. Also note if you registered in the last 5 days, you will need to register again, sorry!
Finaly got the site working as it should – I should say the problem was not wordpress 2.0.1 afterall it was a configuration problem on the server. So I’ll start posting more stuff up more often now :)
Any requests?
Hi,
Can u please tell me what is difference between your XML object connection and this function :
thanks.
Looks like that function is checking the browsers script version before attempting to create the connection. I personally do not see the need as both function use try() anyway. Seems like an extra check which is not needed. Although there are many ways structure code to make the connection. I’ve only given one.
HI.. I downloaded the script but its giving me error, “Request Faild”. I am testing it on windows server. Is there any special configuration required for AJAX to work??
Assumming you are using the correct scripts – then the only configuartion required is in your browser. Most modern Browsers support Ajax, but you must have javascript enabled and Active Scripting (ActiveX) enabled on IE (tools/internet options/advanced). If you still get errors check for white space in those XML files (as mentioned at the end of the article).
Hi there,
Thanks for the tutorial. I’m dealing with an IE oddity that I’m hoping you can help me sort out. I have a similar simple Ajax script for handling responses:
function updateContents(http_request,p_name)
{
if (http_request.readyState == 4)
{
if (http_request.status == 200)
{
var response = http_request.responseXML.documentElement;
var foos = response.getElementsByTagName("foo");
var foo = foos[0];
var myOut = foo.firstChild.nodeValue;
var myParent = document.getElementById(p_name);
var newTr = document.createElement("tr");
var newTd = document.createElement("td");
var newText = document.createTextNode(myOut);
newTd.appendChild(newText);
newTr.appendChild(newTd);
myParent.appendChild(newTr);
}
else
{
alert('There was a problem with the request.');
}
}
}
This works fine for Firefox, however IE gives me problems, saying that response is not an object. I think what’s happening is that http_request.responseXML is not being set because the response headers are specifying ‘Content-Type: text/html’ instead of ‘text/xml’ or ‘application/xml’. I’ve added a line like this to my php script that is opened through the http_request object:
header('Content-Type: application/xml');
but if I print out the headers via javascript, IE still says the content type is “text/html”. Any idea what I’m doing wrong?
Nice guide, I found it really useful, but I have one question: What’s the significance of the documentElement part of the following line?
var response = http.responseXML.documentElement;
I’m currently having a nightmare with AJAX because of something around this area of the script. I can get the data I need, and responseText returns exactly what I requested, but I need it in XML to be able to parse it. My returned XML does return “object XML Document” when I run a typeof on the variable, but for some reason I can’t walk through it pull data out.
[...]
http.onreadystatechange = function () {
if (http.readyState == 4) {
if (http.status == 200) {
response = http.responseXML.documentElement;
check(yti_response);
} else {
alert('Some sort of server error message here');
}
}
}
http.send(null);
}
function check(response) {
status = response.getElementsByTagName("tagname")[0].firstChild.nodeValue;
alert(status);
[...]
It’s all syntactically correct, but for some reason the script just stops running (or gets stuck) when I try to getElementsByTagName. The weirdest thing is that Firefox doesn’t return any kind of JS error whatsoever.
Even stranger is that with .documentElement added to the http.responseXML the script stops running there.
Anyone have any ideas? I’m going crazy…
your header should be:
header(“Content-type: text/xml”);
Hi, I’m trying out this codes on my local machine while I’m using Apache 1.3 and PHP 5.1.2 but I keep on getting the alert box with the message “Response failed”. I think that there is something I missed. Should I configure the php.ini or httpd.conf files? Please help. Thanks.
I’m trying out this codes on my local machine where I’m using Apache 1.3 and PHP 5.1.2 but I keep getting the alert box “Response failed.” after I clicked on the button. What’s wrong? Should I configure the php.ini or httpd.conf files? Please help.
There was a problem with the code in the source-code link, and the demo – it only became apparent once I upgraded tp PHP5.
The problem was the PHP code was refering to the passed in paramaters in the local scope, and not as $_GET['']. Sorry about that folks – it has now been updated and works again. The older version would still have worked if register_globals was on – but we all know that is not the most secure way to code…lol.
How does one fix the above problem on the local scope. please help, i am getting the same problem