2

I have a jQuery ajax call that looks something like this:

jQuery( document ).on( 'mouseover', '#wp-admin-bar-noti-bar-new', function() {

  jQuery.ajax({
    url: "domain.com",
    // etc
    success:function(data){

        // change element id
        jQuery('#wp-admin-bar-noti-bar-new').attr('id','wp-admin-bar-noti-bar');
    }
  });
});

So if ajax call is successful, it changes element. My question is, how do I make it so that if call is unsuccessful after 10 seconds, it should cancel it and do something (like show alert).

How can I do this?

Ashwin Krishnamurthy
  • 3,750
  • 3
  • 27
  • 49
Henrik Petterson
  • 6,862
  • 20
  • 71
  • 155
  • 1
    This question and answers will help you out -> [Abort Ajax requests using jQuery](http://stackoverflow.com/q/446594/1407478) - `.abort()`... – davidkonrad Feb 28 '15 at 16:09

1 Answers1

4

You can set a timeout on the AJAX call and handle that error situation.

jQuery.ajax({
    url: 'domain.com',
    timeout: 10000, // ten seconds in milliseconds
    .
    .
    .
    error: function(request, status, err) {
        if (status === "timeout") {
            alert("Timeout");
        }
    }
});

Note, I used this answer, in part, to formulate my answer.

Once AJAX requests are sent, they are sent. You can't really do too much about them on the server side (see this answer).

You can, however, cancel them on the client side. The request parameter is an jqXHR object which allows you to abort the call using request.abort(); so your function will look something like this:

error: function(request, status, err) {
    if (status === "timeout") {
        request.abort();
        alert("Timeout");
    }
}
Community
  • 1
  • 1
Sumner Evans
  • 8,951
  • 5
  • 30
  • 47