Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abort JSONP ajax request with jQuery

I'm using a JSONP ajax call to load some content from a different domain, and all this stuff is executed if the user causes a "mouseover" on a button.

I can capture the $.ajax() call return as a xhr object, and use it to abort the ajax request each time the user causes a "mouseover". But the JSONP callback function still gets called, and this causes an error, and I think it is beacuse the xhr.abort() method does not prevent the callback function to be called.

I've tried surrounding the $.ajax() call with try{}catch(e){}, but after I call the xhr.abort() method, the error continues.

Is there a way to handle that exception?

The raised exception is like this (according to Firebug): jQuery16102234208755205157_1308941669256 is not a function

And the exception's internal structure is like this: jQuery16102234208755205157_1308941669256({... my json data from a different domain....})

like image 828
David Avatar asked Jun 24 '11 18:06

David


1 Answers

The basic answer is simply the one given here: You can't really abort() a JSONP call. So the real question is, how do you avoid both superfluous callback invocations and the error you're seeing?

You can't use try...catch around the callback because it's asynchronous; you'd have to catch it from jQuery's end, and jQuery generally doesn't handle exceptions thrown from callbacks. (I discuss this in my book, Async JavaScript.) What you want to do instead is use a unique identifier for each Ajax call and, when the success callback is invoked, check whether that identifier is the same as it was when you made the call. Here's an easy implementation:

var requestCount = 0;
$.ajax(url, {
  dataType: 'jsonp',
  requestCount: ++requestCount,
  success: function(response, code) {
    if (requestCount !== this.requestCount) return;
    // if we're still here, this is the latest request...
  }
});

Here I'm taking advantage of the fact that anything you pass to $.ajax is attached to the object that's used as this in the callback.

It'd be nice if jQuery made abort() do this for us, of course.

like image 152
Trevor Burnham Avatar answered Oct 21 '22 09:10

Trevor Burnham