Martin AJ
Martin AJ

Reputation: 6697

How can I abort an ajax request if it took a while?

Here is my code:

$("input").on('keydown', function(){
    $.ajax({
        url :  '/files/tags_autocomplete.php',
        dataType : 'JSON',
        success : function (tags) {
            $("ul").html(tags.output);
        }
    });
});

It works as well and all fine. Just sometimes tags_autocomplete.php returns a response after 8sec (which is too much) or sometimes it totally fails and doesn't return a response.

Anyway, I want to make a something went wrong mechanism which should be run 4sec after sending that ajax request. How can I do that?

Upvotes: 0

Views: 812

Answers (1)

Sanchay Kumar
Sanchay Kumar

Reputation: 566

You can specify a timeout

You can catch error after timeout

$("input").on('keydown', function(){
    $.ajax({
        url :  '/files/tags_autocomplete.php',
        dataType : 'JSON',
        success : function (tags) {
            $("ul").html(tags.output);
        },
        error : function (jqXHR, textStatus, errorThrown) {

        },
        timeout: 4000
    });
});

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

Upvotes: 3

Related Questions