Question

I want to abort a request through $.ajax() but I'm keep getting Uncaught TypeError: Object 5 has no method 'abort'. The number 5 changes to 10 after one more click and then if you click some more times, it just keeps going up. I am using the following code:

var load_info = '';

$('body').on('click', '#moreinfo', function() {
    load_info = setTimeout(function(){
        $.ajax({
            url:'file.php',
            method:"GET",
            success:function(s){ alert(s); },
            error:function(e){ alert(e); }
        })
    },2000);
});

$('body').on('click', '#cancel', function() {
    load_info.abort();
});

Demo at jsFiddle (bring up browser's console to see the error)

How can I make this function to work?

Était-ce utile?

La solution

As the error says, numbers don't have an abort method. Your load_info is a number, the handle returned by setTimeout. It's not an XHR or jqXHR object.

If you want to cancel the timer (prevent the ajax request from being started), use:

clearTimeout(load_info);

If you want to cancel the in-progress ajax call once it is started, you'll have to get the XHR object from ajax and then call abort on it, like this:

var loading_xhr = null;

$('body').on('click', '#moreinfo', function() {
    setTimeout(function(){
        loading_xhr = $.ajax({
            url:'file.php',
            method:"GET",
            success:function(s){ alert(s); },
            error:function(e){ alert(e); },
            complete:function(){
                // Be sure to clear it again here
                loading_xhr = null;
            };
        })
    },2000);
});

$('body').on('click', '#cancel', function() {
    if (loading_xhr) {
        loading_xhr.abort();
        loading_xhr = null;
    }
});

Autres conseils

setTimeout() returns a number:

the numerical ID of the timeout, which can be used later with window.clearTimeout().

>>> var x = window.setTimeout(function(){}, 1000)
undefined
>>> x
102
>>> typeof x
"number"

I suspect you want what the documentation suggests:

window.clearTimeout(load_info);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top