0

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?

Martin AJ
  • 6,261
  • 8
  • 53
  • 111
  • 1
    Possible duplicate of [Abort Ajax requests using jQuery](http://stackoverflow.com/questions/446594/abort-ajax-requests-using-jquery) – chiliNUT Apr 25 '17 at 15:55
  • @chiliNUT While that may work, timeout would be a better fit. This would be a better duplicate: http://stackoverflow.com/questions/5225597/set-timeout-for-ajax-jquery – Blue Apr 25 '17 at 16:03
  • Possible duplicate of [Set timeout for ajax (jQuery)](http://stackoverflow.com/questions/5225597/set-timeout-for-ajax-jquery) – Blue Apr 25 '17 at 16:04

1 Answers1

3

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/

Sanchay Kumar
  • 566
  • 5
  • 11
  • Well I need to know when `timeout` is executed. Because I have to show a pop-up contains *"something went wrong"* message. How can I when `timeout` is executed? – Martin AJ Apr 25 '17 at 15:57
  • @MartinAJ http://stackoverflow.com/questions/3543683/determine-if-ajax-error-is-a-timeout – Blue Apr 25 '17 at 16:01
  • The `fail` or `error` callbacks will be used then when it times out. – trevster344 Apr 25 '17 at 16:02
  • @MartinAJ when it errors out, call a function from the error handling function to display an alert or some other message – henry Apr 25 '17 at 16:06
  • @trevster344 `fail` and `error` are exactly the same? – Martin AJ Apr 25 '17 at 16:07
  • Depends on which Ajax methods you use. On $.ajax I use the error callback. On $.get or $.post I use the fail callback. – trevster344 Apr 25 '17 at 16:10