Ajax function question

I’m trying to figure out why my ajax script is not working. For example only (not complete code):

request = new XMLHttpRequest();
request.onreadystatechange = function () {
if(request.readyState == 4) {
if(request.status ==200) {
some code }

Can I name this function by putting a name between the word “function” and the “()” on the

“request.onreadystatechange = function() {” line above, then call it by name with an event handler?

Even though this code is incomplete, did I make any mistakes?

Thanks

Can I name this function by putting a name between the word “function” and the “()”… then call it by name with an event handler?

Nope. Try the following for proof:


request = new XMLHttpRequest();
request.onreadystatechange = function test() {
    alert('WAZZA');
};

alert(test); // ERROR: "test is not defined""

The good news is there’s a pretty easy way to do what you want: Define the function first, and then assign it:


function test() {
    alert('WAZZA');
}

request = new XMLHttpRequest();
request.onreadystatechange = test;

someElement.addEventListener('someEvent', test, false);

Even though this code is incomplete, did I make any mistakes?

You didn’t use the “var” keyword to create your request variable. When you assign something to a variable without using “var”, you actually create a global variable. So it’s not really a mistake per se, as long as you’re aware of what you’re doing, but it makes the hairs on the back of my gritted teeth stand on end.

It looks like you never closed the onreadystatechange function, but that could just be because your sample is incomplete.

As it stands, there’s no support for IE6, which doesn’t have the XMLHttpRequest function. You need to use ActiveXObject instead:


request = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');

…But that’s only if you care about IE6. If you don’t, then no worries!

Very helpful. Thanks for taking the time.

For supporting ajax2 in IE (before 10) you need to use XDomainRequest instead.