0

I'm running a long polling ajax that returns status of request. If failed, I need the ajax to stop. The ajax is written like this:

function someFunction(url){
    $.ajax({
        url: url,
        success: function(data){
            if(data.status == 'FAILED'){
                //Need this ajax to stop
            }
        }
    });
}



$('some-button').on('click',function(
    var url = 'server-url';
    someFunction(url);
));

I have to use the someFunction() function as this long polling method is being used by multiple other parts of the code. What should I be doing to stop this function?

Newtt
  • 6,050
  • 13
  • 68
  • 106
  • See this http://stackoverflow.com/questions/4551175/how-to-cancel-abort-jquery-ajax-request – web-nomad Apr 04 '14 at 07:25
  • Stop how, by the time data is returned, it's done ? – adeneo Apr 04 '14 at 07:26
  • @AnantDabhi - how would that work exactly, by the time it's failed or successful, it's a little late to start aborting the call, as it's already complete ? – adeneo Apr 04 '14 at 07:33

3 Answers3

0

$.ajax returns a wrapped xhr object. Simply use:

var req = $.ajax...
..
req.abort()
aurbano
  • 3,324
  • 1
  • 25
  • 39
Mauro Valvano
  • 903
  • 1
  • 10
  • 21
0

try something like this

     function someFunction(url){
        $.ajax({
            url: url,
            success: function(data){
                if(data.status != 'FAILED'){
                    //Need this ajax to stop
                }
            }
        });
    }

your ajax request is already completed in success. but if status is failed and you want to stop further execution of code than you can use not !

rajesh kakawat
  • 10,826
  • 1
  • 21
  • 40
0
var ajaxReq = null;
ajaxReq = $.ajax({
        url: url,
        success: function(data){
            if(data.status == 'FAILED'){
                //Need this ajax to stop                     
            }
        }
        error: function (x, y, z) {
            ajaxReq.abort();
       }
    });

And you can use ajaxReq.abort() to stop ajax call.

Girish Vadhel
  • 735
  • 1
  • 5
  • 17
  • You are writing the `abort` call in the `success` handler, which means the ajax request has already completed, isn't it. What would calling `abort` do? – web-nomad Apr 04 '14 at 07:45
  • @web-nomad, exactly the problem I faced while trying this solution. I don't think this is the correct solution. – Newtt Apr 04 '14 at 07:55