Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to kill an older jsonp request?

Tags:

jquery

jsonp

I have a cross-domain long polling request using getJSON with a callback that looks something like this:

$.getJSON("http://long-polling.com/some.fcgi?jsoncallback=?"
    function(data){
          if(data.items[0].rval == 1) {
            // update data in page
          }
    });

The problem is the request to the long-polling service might take a while to return, and another getJSON request might be made in the meantime and update the page even though it is a stale response.

Req1: h**p://long-polling.com/some.fcgi at 10:00 AM

Req2: h**p://long-polling.com/some.fcgi? at 10:01 AM

Req1 returns and updates the data on the page 10:02 AM

I want a way to invalidate the return from Req1 if Req2 has already been made.

Thanks!

like image 254
pfg Avatar asked May 04 '10 12:05

pfg


3 Answers

I don't think that works as the getJSON uses JSONP method which actually works by dynamically inserting a script tag which your browser executes. I don't think there is any way to stop the browser from executing the script...is there?

like image 117
mayas_mom Avatar answered Nov 13 '22 02:11

mayas_mom


When you make the ajax request it returns the XMLHttpRequest object. If you want to abort the call you can call the .abort() method on it.

var request = $.getJSON(. . . . . );
request.abort();
like image 5
PetersenDidIt Avatar answered Nov 13 '22 00:11

PetersenDidIt


As @NewToDB mentioned, you cannot cancel the jsonp request (e.g. tell the browser to stop trying to load the src of a tag), but you could implement a mechanism that effectively ignores the returned data of the old call. Define a global variable that is incremented each time you are going to make the jsonp call and pass the value of that variable to the server as a parameter. You also need to pass it the counter back from the server (I'm assuming you also own the server code). If the current value of your counter is not equal to the returned counter value then you know that another server call has already been made, so you can ignore the returned data.

// Global counter
var callCounter = 0;

...

$.getJSON("http://long-polling.com/some.fcgi?callCounter=" + (++callCounter) + "&jsoncallback=?"
    function(data){
          if(data.items[0].rval == 1 && data.callCounter == callCounter) {
            // update data in page
          }
    });
like image 1
PPrice Avatar answered Nov 13 '22 00:11

PPrice