Thursday 6 September 2007

The XMLHttpRequest object

This is AJAX related, and likely to cause problems if you're doing what I'm doing.

I use the object to write out some HTML into a div of a page.

The HTML I'm writing is from an ASP file, and so the syntax for the (pre-declared object) looks like this:

url = "searchDBaseAjax.asp?" + savedUrl;
url=url+"&sid="+ Math.random();

xmlHttp.onreadystatechange=caravanSearchStateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);


Now if youre searchDBaseAjax.asp file contains some javascript that you want to write to that div, and you want it to happen straight away, you'll have problems.

Say you put a hidden input field in your ASP file.

Say that you then want to test this within the function that you write your ASP file from (just below the code mentioned above).

if (document.getElementById('hideHeaders').value == '1') {
document.getElementById('resultsHeader').className = ' none';
}
else {
document.getElementById('resultsHeader').className = 'floatleft paddingtop15';
}

Because this is an asynchronous call, it's likely that the processing of the AJAX method will not be completed by the time that your javascript underneath executes, and therefore your input field will not be tested properly.

One solution was to make this method synchronous. (Change the true in the open method to false). Trouble is, that doesn't work.

So to fix it, I used the xmlHttp.onreadystatechange attribute to specify the method caravanSearchStateChanged which is mentioned in the first code-snippet.

That method now looks like this:

function caravanSearchStateChanged()
{
if (xmlHttp.readyState==4)
{
document.getElementById("ajaxSearchResults").innerHTML=xmlHttp.responseText;

if (document.getElementById('hideHeaders').value == '1') {
document.getElementById('resultsHeader').className = ' none';
}
else {
document.getElementById('resultsHeader').className = 'floatleft paddingtop15';
}
}
}

So basically, the ready state for our open method is 4 and I've checked that this is the case before I fire off my new javascript that tests the input field.

Days of messing about, this took.

For more information, check out the MSDN entry.

No comments: