49

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.

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
Mr_Nizzle
  • 6,644
  • 12
  • 55
  • 85

4 Answers4

85
$.ajax({
    url : 'my_action',
    dataType: 'script',
    beforeSend : function(xhr, opts){
        if(1 == 1) //just an example
        {
            xhr.abort();
        }
    },
    complete: function(){
        console.log('DONE');
    }
});
thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
  • 4
    And if you use `$(document).on("ajax:beforeSend", ".my-selector", function(e, xhr) { … })`, note that the `xhr` argument is the second one. – Henrik N May 12 '15 at 12:18
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');
    }
});
Farhan Ahmad
  • 5,148
  • 6
  • 40
  • 69
  • 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. – Triynko Dec 01 '15 at 20:43
6
beforeSend:function(jqXHR,setting)
{
    // if(setting.url != "your url") jqXHR.abort();
    if(1 == 1) //just an example
    {
        jqXHR.abort();
    }
}
The Alpha
  • 143,660
  • 29
  • 287
  • 307
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.

JSON
  • 1,583
  • 4
  • 31
  • 63