Sunday, June 8, 2008

XmlHttp ajax style code to call a script without reloading the page

One of the more useful snippets of code I’ve harvested from the web is something that does Ajax

style requests.

I’m using it more and more for all sorts of stuff. I’ve found it to be pretty bomb-proof so far. It’s been tested in Firefox and IE, and I think Safari also, and it always works.

I’d love to credit someone for it, but I have no idea where I got it from. (it was quite a long time ago)

So here’s how it works…

First of all you need the to build the object to run the request.

That’s done with the xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); bits. Depending on the browser, it makes an ActiveXObject or an new XMLHttpRequest();

Then you specify the script you want to execute. I’ve found it works best if the script is in the same folder as the calling page.

The xmlHttp.onreadystatechange = whatHappened; line specifies the function to call when the script has executed.

Note you don’t put the ‘()’ after it yet.

Then you open the connection - xmlHttp.open("POST", url, true); you can specify GET or POST to send your info into the script. I use POST pretty much all the time.

Then set up the parameter list to send to the script. It’s just like setting up the parameters to send through as GET variables – parameterName=value.

You then set up the headers to send, and then send the request.

In the whatHappened() function (which you can call whatever you want) you test for the ‘readyState’. 4 means that the script has finished executing and has returned.

Then you can do whatever you want with the returned data.

To return from a PHP script make sure you use an echo statement, not a return statement.

Because you’re using an echo the returned data is in the form of a string. You can set up the format of the string so that it is delimited, making it easy to split into variable to use in the Javascript function.

Try it yourself. You’ll find this is a handy little script to have in your arsenal.

try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");

} catch (e) {

try {

xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

} catch (e2) {

xmlHttp = false;

}

}

if (!xmlHttp && typeof XMLHttpRequest != "undefined") {

xmlHttp = new XMLHttpRequest();

}

// Build the URL to connect to

var url = "scriptToExecute.php";

xmlHttp.onreadystatechange = whatHappened;

// Open a connection to the server

xmlHttp.open("POST", url, true);

//get values from the form

var parameters = "parameterName=" + encodeURI( parameterValue);

xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

xmlHttp.setRequestHeader("Content-length", parameters.length);

xmlHttp.setRequestHeader("Connection", "close");

xmlHttp.send(parameters);

return false;

}

function whatHappened(){

if(xmlHttp.readyState==4){

// do stuff

}

}

No comments: