How to get errors in AJAX requests?

0

I need to get errors in sending the request and treat them in the application, briefly the function works this way.

link

I have not put the same one that is in my application to simplify the resolution of the problem, the difference is that in my application it has callbacks for the requests.

It works perfectly when the request is completed, then I get the data and the application continues, however when any failure occurs, none of the alerts I put to indicate that at least it fell in the execution block is called.

Another error that I can not get is if the user loses the connection to the internet, it is possible to test in the browser itself, in case Chrome has an option to simulate that it is disconnected, the console is generating an error described as net::ERR_INTERNET_DISCONNECTED , but I did not fall into any block of execution that I can handle the problem.

How can I get error requests for AJAX requests?

I do not want to use JQuery or any other library.

    
asked by anonymous 12.07.2016 / 02:01

1 answer

1

Hello Renan, I understand your error, this is the following when you make a request and it is without internet, your request is interpreted as a request for another domain, thus causing this CORS problem, to solve this, simply add the header that enables the CORS of any domain, follows the code:

function send (method, url, data)
{      
    var xhr = new XMLHttpRequest();

    xhr.ontimeout = function()
    {
        alert('timeout');
    }

    xhr.onload = function() 
    {
        if (xhr.readyState === 4) 
        { 
            if (xhr.status === 200) 
            {
                alert('success');
            } 
            else 
            {
                alert('failed');
            }
        }
        else
        {
            alert('failed');
        }
    };

    try
    {
        xhr.timeout = 10000;
        xhr.setRequestHeader('Access-Control-Allow-Origin', '*') //Linha modificada.
        xhr.open(method, url, true);
        xhr.send(data);
    }
    catch(er)
    {
        alert('failed');
    }
}

send('POST', '/echo/jsonp/', null);
    
12.07.2016 / 04:57