Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop $.ajax on beforeSend

Tags:

jquery

ajax

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.

like image 579
Mr_Nizzle Avatar asked May 08 '12 21:05

Mr_Nizzle


People also ask

How do I stop ajax calls?

We may use the abort() method to cancel a sent AJAX request.

Are ajax calls blocking?

ajax has async property. If you set it to false it will block. possible duplicate of Synchronous calls with jquery -- you cannot block the runtime without blocking the browser though.

Is there any way to wait for ajax response and halt execution?

Cut and paste whatever code you need to execute in the callback function passed to success . Some good answer is already provided.


2 Answers

$.ajax({     url : 'my_action',     dataType: 'script',     beforeSend : function(xhr, opts){         if(1 == 1) //just an example         {             xhr.abort();         }     },     complete: function(){         console.log('DONE');     } }); 
like image 145
thecodeparadox Avatar answered Sep 20 '22 18:09

thecodeparadox


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');     } }); 
like image 23
Farhan Ahmad Avatar answered Sep 18 '22 18:09

Farhan Ahmad