Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set maximum execution time for ajax post with jQuery?

Is there a way to specify maximum execution time of an ajax post to the server so if the server doesn't respond, then keep trying for 10 seconds and then continue with the rest of the code??

Function doajaxPost(){
    var returned_value="";

    // #############I NEED THIS CODE TO TRY TO POST THE DATA TO THE SERVER AND KEEP
    // #############TRYING FOR 10 SECONDS AND THEN CONTINUE WITH THE REST OF THE CODE.
        jQuery.ajax({
            url: 'ajaxhandler.php',
            success: function (result) {                               
                returned_value=result;
            },
            async: false
        });
    // ###################################################

    alert(returned_value);

    some other code
    .
    .
    .           
 }
like image 613
themhz Avatar asked Apr 27 '12 16:04

themhz


2 Answers

Use timeout:

jQuery.ajax({
    url: 'ajaxhandler.php',
    success: function (result) {                               
        returned_value=result;
    },
    timeout: 10000,
    async: false
});

However, alert(returned_value); will execute just after your call (won't wait for the call to finish).

like image 151
ilyes kooli Avatar answered Sep 20 '22 23:09

ilyes kooli


The JQuery API documentation tells how to set a "timeout".

http://api.jquery.com/jQuery.ajax/

While other answers here are correct, learning to check the documentation for yourself is more valuable than knowing just this answer.

like image 26
John Fisher Avatar answered Sep 19 '22 23:09

John Fisher