Bggreen
Bggreen

Reputation: 123

XMLHttpRequest Open and Send: How to tell if it worked

As is in the title, my question is, Is is possible to tell if the open and send methods from XMLhttpRequest actually worked? Is there any indicator? example code:

cli = new XMLHttpRequest();
cli.open('GET', 'http://example.org/products');
cli.send();

I'm trying to code in fault handling to this, but I need to be able to tell if the request failed so I can handle it.

Upvotes: 2

Views: 10246

Answers (2)

Denys Séguret
Denys Séguret

Reputation: 382394

This is an an asynchronous operation. Your script continues its execution while the request is being sent.

You detect the state changes using a callback :

var cli = new XMLHttpRequest();
cli.onreadystatechange = function() {
        if (cli.readyState === 4) {
            if (cli.status === 200) {
                       // OK
                       alert('response:'+cli.responseText);
                       // here you can use the result (cli.responseText)
            } else {
                       // not OK
                       alert('failure!');
            }
        }
};
cli.open('GET', 'http://example.org/products');
cli.send();
// note that you can't use the result just here due to the asynchronous nature of the request

Upvotes: 3

Hank
Hank

Reputation: 1

req = new XMLHttpRequest;
req.onreadystatechange = dataLoaded;
req.open("GET","newJson2.json",true);
req.send();

function dataLoaded()
{
    if(this.readyState==4 && this.status==200)
    {
        // success
    }
    else
    {
        // io error
    }
}

Upvotes: -1

Related Questions