Search code examples
javascriptajaxtimeout

Ajax Timeout Not Working and Not Showing "Timeout" Status


I am trying to do a connection check for a form before it is submitted, when the button is clicked on. The idea is to look through a Timeout request "Timeout()..." which is not implemented yet in this code, and keep iterating through the Ajax until a connection is found, as sometimes out in the field the connection can drop. When a connection is found it will alert the user and will submit successfully if there was a dropped connection after hitting submit. Here is what I have so far:

function upload_prepformDiff() {
$.ajax({
        type: 'POST',
        url: './php/upload_prepform.php',
        timeout: 2000, //2 seconds, for testing purposes
        data: prepform,
        async: false,//Omitted now as of this post
        dataType: 'text',
        success: function() {
            alert("Your Prep form has been submitted.");
            window.top.location.replace('./');
        },

        error: function (xhr, status, error) {
            if(status == "timeout") {
                alert("Internet connection has been lost! Please wait until you are notified and do not continue.");
            } else {
                alert(status + " " + error);
            }
        }
});
};

The issue is that even with a low timeout value, I do not get a "timeout" status message I get "error." So it never throws the timeout error I need and for error I get: Error: NETWORK_ERR: XMLHttpRequest Exception 101

So the ajax does notice there is no connection, but that is what the errorThrown shows, while the textStatus is "error" for (xhr, status, error) respectively. So what I TRIED doing was do a little improvising and do some type of error.indexOf() deal with the error string thrown in the Ajax, but that didn't work nor did error.contains("NETWORK_ERR") or any type of Regex command. Any ideas for improving this or why I am not getting a timeout? Thanks!


Solution

  • Guess this might be a bit late for you, but nevertheless...

    If you have specified

    async as 'false'

    , the timeout property will be ignored.

    As for handling the errors, you can visit an earlier SO question: status of ajax or post request

    Hope this helps! :)