views:

408

answers:

2

Hi there,

I have a report in our internal system that can return anywhere from 1 days data to a full years. Because of this, the report can take 0.5 seconds or over 45 seconds to generate everything.

The report lets you modify a bunch of filters, all which when modified, fire off an ajax request very simply:

var ax = $.ajax({
    type: "GET",
    url: "/blah",
    data: values,
    success: function(data) { .. }
});

Now, the problem comes when our wonderful user states "Oh wait! I want this to be from February, not January!". But, a request is already happening since January is a lot of data! So, the user switches the date option to February and I can see the Javascript console sending out a second request. Now we have two going and it's a race!

/report/?start_date=January (Still Loading...)

/report/?start_date=February (Hey, I'm here now too!)

Then, usually the smaller one will load sooner, but then the other one loads and it over-writes the one they already had .. hmm :)

I've tried using ax.abort() placed after the declaration of the ax variable as mentioned here but it doesn't seem to be working.

So now I wonder, what am I missing? I just want to kill the current request (client side, I know I can't do anything about it on the server side) as soon as the user changes some options so I don't have 2 or more requests going at the same time. Setting async: false is not an option as it just locks the user out.

Thanks in advance for your help.

+1  A: 

You may take a look at the ajaxmanager plugin.

Darin Dimitrov
Looks very easy to use, thanks. Will try this out
Bartek
This worked out great. Thanks for the reference
Bartek
+2  A: 

I think that trying to abort previous request is not a good solution. Maybe you should use simple workaround - for each ajax request increase counter in javascript, and pass it to the ajax callback. When the callback occurs check if the counter of the response is the same as the current counter value. If not, then ignore the response - it was fired by outdated click event.

PanJanek
Heh, not a bad solution. Pretty simple, but curious how it'd work in application. Will have to try it tomorrow
Bartek
good idea! will try implement this in my one
The_Butcher