0

I would like to manage an ajax call with timeout with .when and .then.

I have a script like this:

$.when(
        $.ajax({   
            url: url_ajax, 
            type: "GET", 
            async: true,
            data: window.location.search, 
            dataType: "json", 
            timeout: 30000,
            success: function(data) {
                console.log('ok');
            },
            error: function(data) {

            }
        }),
        $.ajax({   
            url: url_ajax, 
            type: "GET", 
            async: true,
            data: window.location.search, 
            dataType: "json", 
            success: function(data) {
                console.log('ok');
            },
            timeout: 30000,
            error: function(data) {

            }
        })
     ).then(function() {
          alert('end');
     });

If an ajax request go in timeout the callback .then isn't called and I can't see the last alert. So if my ajax request go in timeout I can't exit enter into then function.

I have also tried to add this after each ajax request:

.fail(function(jqXHR, textStatus){
            if(textStatus == 'timeout')
            {     
                alert('Failed from timeout'); 
            }
         })

But again doesn't enter into then function

How can I manage timeout? Thanks

Alessandro Minoccheri
  • 35,521
  • 22
  • 122
  • 171

1 Answers1

1

Have you tried using .then(successCallbackFunction, failCallbackFunction) like so:

$.when(
    $.ajax({   
        url: url_ajax, 
        type: "GET", 
        async: true,
        data: window.location.search, 
        dataType: "json", 
        timeout: 30000,
        success: function(data) {
            console.log('ok');
        },
        error: function(data) {

        }
    }),
    $.ajax({   
        url: url_ajax, 
        type: "GET", 
        async: true,
        data: window.location.search, 
        dataType: "json", 
        success: function(data) {
            console.log('ok');
        },
        timeout: 30000,
        error: function(data) {

        }
    })
 ).then( // success
         function() {
           alert('Success!');
         },
         // failure
         function(jqXHR, textStatus){
            if(textStatus == 'timeout')
            {     
                alert('Failed from timeout'); 
            } else {
                alert('Failed from: '+textStatus);
            }
         }
 );
mccannf
  • 16,619
  • 3
  • 51
  • 63
  • There is a little problem, if the first is aborted go immediately to failure function before the second end. I would like to have a failure function run when all request finished if there is an error. is possible? – Alessandro Minoccheri Sep 19 '14 at 07:08
  • You need something custom for that. See the second answer to this question: http://stackoverflow.com/questions/5518181/jquery-deferreds-when-and-the-fail-callback-arguments – mccannf Sep 19 '14 at 08:43