Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeat failed XHR

Is there any common way, example or code template how to repeat a XHR that failed due to connection problems? Preferably in jQuery but other ideas are welcome.

I need to send some application state data to a database server. This is initiated by the user clicking a button. If the XHR fails for some reason I need to make sure that the data is sent later (no interaction needed here) in the correct order (the user may press the button again).

like image 596
Mq_ Avatar asked Jan 25 '12 15:01

Mq_


1 Answers

Here's how I would do it:

function send(address, data) {

    var retries = 5;

    function makeReq() {


        if(address == null)
            throw "Error: File not defined."

        var req = (window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");

        if(req == null)
            throw "Error: XMLHttpRequest failed to initiate.";

        req.onload = function() {
            //Everything's peachy
            console.log("Success!");
        }
        req.onerror = function() {
            retries--;
            if(retries > 0) {
                console.log("Retrying...");
                setTimeout(function(){makeReq()}, 1000);
            } else {
                //I tried and I tried, but it just wouldn't work!
                console.log("No go Joe");
            }
        }

        try {
            req.open("POST", address, true);
            req.send(data); //Send whatever here

        } catch(e) {
            throw "Error retrieving data file. Some browsers only accept cross-domain request with HTTP.";
        }


    }
    makeReq();

}


send("somefile.php", "data");

To make sure everything is sent in the right order, you could tack on some ID variables to the send function. This would all happen server-side though.

And of course, there doesn't need to be a limit on retries.

like image 82
Jeffrey Sweeney Avatar answered Oct 22 '22 13:10

Jeffrey Sweeney