Stop $.ajax on beforeSend
Asked Answered
D

4

51

I have this jQuery ajax call:

$.ajax({
    url : 'my_action',
    dataType: 'script',
    beforeSend : function(){
        if(1 == 1) //just an example
        {
            return false
        }
    },
    complete: function(){
        console.log('DONE');
    }
});

I want to stop the ajax call under the beforeSend if the condition returns true but return false does not stop the ajax call.

How can I stop the ajax call on the beforeSend?

======= UPDATE =========

return false works as well.

Doublefaced answered 8/5, 2012 at 21:49 Comment(1)
Possible duplicate of #447094Pressman
A
86
$.ajax({
    url : 'my_action',
    dataType: 'script',
    beforeSend : function(xhr, opts){
        if(1 == 1) //just an example
        {
            xhr.abort();
        }
    },
    complete: function(){
        console.log('DONE');
    }
});
Ataghan answered 8/5, 2012 at 21:53 Comment(1)
And if you use $(document).on("ajax:beforeSend", ".my-selector", function(e, xhr) { … }), note that the xhr argument is the second one.Coopersmith
T
10

Most of the jQuery Ajax methods return an XMLHttpRequest (or the equivalent) object, so you can just use abort().

var test = $.ajax({
    url : 'my_action',
    dataType: 'script',
    beforeSend : function(){
        if(1 == 1) //just an example
        {
            test.abort();
            return false
        }
    },
    complete: function(){
        console.log('DONE');
    }
});
Tasker answered 8/5, 2012 at 21:53 Comment(1)
There is a dangerous assumption here that beforeSend is not called before the ajax method returns. You're passing an object with beforeSend into the ajax method, so the ajax method could call it long before returning to set the value of test. If the ajax method calls beforeSend synchronously (i.e. before it returns anything), then test will not have a value while beforeSend runs. That would be an error. It would be safer to call abort on the jqXHR object that's passed to beforeSend, like the other answer in this thread.Bionics
S
6
beforeSend:function(jqXHR,setting)
{
    // if(setting.url != "your url") jqXHR.abort();
    if(1 == 1) //just an example
    {
        jqXHR.abort();
    }
}
Stillwell answered 8/5, 2012 at 21:54 Comment(0)
S
5

xhr.done(); this works for me

$.ajax({
    url : 'my_action',
    dataType: 'script',
    beforeSend : function(xhr){
        if(1 == 1) //just an example
        {
            return false
        };
        xhr.done(); //this works for me
    },
    complete: function(){
        console.log('DONE');
    }
});

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

jqXHR.done(function( data, textStatus, jqXHR ) {});

An alternative construct to the success callback option, refer to deferred.done() for implementation details.

Sneaking answered 7/7, 2016 at 19:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.