Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax won't get past readyState 1, why?

I'm trying to get this function to work, which does a request for parameter url then sends the responseText to callback which is a function.

It seems that it only gets to readyState 1 (thanks to the Firebug commands).

Here it is:

function Request(url, callback){
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
    httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
} else{
    return false;
}
httpRequest.onreadystatechange = function(){
    console.log(httpRequest.readyState);
    if (httpRequest.readyState == 4) {
        callback(httpRequest.responseText);
    }
};
console.log(httpRequest, url);
httpRequest.open('GET', url, true);
httpRequest.send(null);
}
like image 960
kennyisaheadbanger Avatar asked Apr 15 '09 11:04

kennyisaheadbanger


People also ask

What does readyState 1 mean?

readyState. Holds the status of the XMLHttpRequest. 0: request not initialized. 1: server connection established. 2: request received.

How many readyState status are present in Ajax?

readyState is an XMLHttpRequest property. There are five ready states of a request as listed below: readyState=0.

What does readyState 3 mean?

Having the readyState with a value of 3 it means that the current state is LOADING .


2 Answers

I workarounded this problem assigning onload event instead of onreadystatechange:

function Request(url, callback){
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
    httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
} else{
        return false;
}

var readyStateChange = function(){
    console.log(httpRequest.readyState);

    if (httpRequest.readyState == 4) {
                callback(httpRequest.responseText);
    }
};


if (isFirefox && firefoxVersion > 3) {
    httpRequest.onload = readyStateChange;
} else {
    httpRequest.onreadystatechange = readyStateChange;
}

console.log(httpRequest, url);
httpRequest.open('GET', url, true);
httpRequest.send(null);
}
like image 58
Svitlana Maksymchuk Avatar answered Sep 23 '22 14:09

Svitlana Maksymchuk


Check that the URL in question does actually respond by visiting it directly in the browser.

Test with a different browser do you get the same result.

Use some form of HTTP monitor to watch the client to server conversation (my favorite is Fiddler)

like image 38
AnthonyWJones Avatar answered Sep 21 '22 14:09

AnthonyWJones