5

My requirement is ,I have written lots of $.post method in my project. I want to check the session in every request and depending upon the session value, I want to handle my page.But I don`t want to modify all methods($.post) for session, So I want to check the session in "ajaxStart or ajaxSend" and depending upon the response I want to abort the main AJAX call.

I have tried with my little knowledge.The below sample code is not working,because $.post is asynchronous.Could any one help me to abort an AJAX Request in ajaxStart or ajaxSend state?

var pp;
link=function(id){
var url="http://localhost/jqueryui/test.php";
    pp=$.post(url,{"id":id},function(data){
        $("#div"+id).html(data);
    });
}
$(function(){
    $("#loading").ajaxStart(function(){
        alert("Hi start");
        $(this).show();
               var url="http://localhost/jqueryui/test.php";
           $.post(url,{"id":99},function(data){//checking the session
            if(data == "close")
            pp.abort();         
            });
    }); 
});
3
  • @corroded: I am agree,what you have suggested.But I have to made more changes to my code.Because of this reason I am searching some alternative solution.
    – Priyabrata
    Commented Apr 4, 2011 at 13:24
  • i do think that that is more feasible than trying to hack your way with aborting ajax calls. it's a waste of ajax calls.
    – corroded
    Commented Apr 4, 2011 at 13:39
  • possible duplicate of Stop jquery ajax request in ajaxStart
    – Barun
    Commented Nov 8, 2013 at 9:54

2 Answers 2

5

You can abort the request by using the second paramter "jqXHR" in the callback:

$( document ).ajaxSend( function( event, jqXHR, ajaxOptions )
{
    jqXHR.abort(); // aborts the ajax request
} );
1

See beforeSend(jqXHR, settings) from the jQuery website. I don't know what version of jQuery you were using, but the docs say that you can return false from beforeSend to cancel.

Not the answer you're looking for? Browse other questions tagged or ask your own question.