0

Possible Duplicate:
Ajax request in progress jQuery

what I try to achieve is something like :

var calling = {};
if(!calling[resourceId]){
    $.ajax(...);
    calling[resourceId] = true;
}

Obviously, I want to avoid making two calls for the same resource at the same time. But I find it ugly to use a global variable across my scripts for this. I would like to know if you knew a nice way to handle this directly with jQuery ?

The best solution that I can think of is a monkey patch on jQuery.ajax to provide it with some "resourceId" parameter, and before any call the jQuery.ajax() function itself would check if a call is already being made with that "resourceId". I could not find such an option in the $.ajax documentation and I wonder why !?

Thank you.

UPDATE: I found exactly what I was looking for on in jQuery's Prefilters option, on the "Extending Ajax" documentation page. : http://api.jquery.com/extending-ajax/

Thanks for tips people :)

Community
  • 1
  • 1
Louis Ameline
  • 2,779
  • 1
  • 25
  • 25
  • 1
    You can use the same concept without having to make your variables attached to `window`. I usually wrap up this kind of communication in a class. – Brad Oct 31 '12 at 17:34
  • 1
    If its a get query then in normal settings it is cached by browser. You can use it to ur advantage. – Subir Kumar Sao Oct 31 '12 at 17:36
  • @Brad: on window or a custom class, I still find it messy, I feel it should be handled by $.ajax itself. Rory : maybe duplicate, but the answer there was not satisfying. Subirkumarsao: when the query is being made, it is not cached yet – Louis Ameline Oct 31 '12 at 17:49
  • Maybe [jQuery.whenSync() Plugin For Chaining Asynchronous Callbacks Using Deferred Objects](http://www.bennadel.com/blog/2326-jQuery-whenSync-Plugin-For-Chaining-Asynchronous-Callbacks-Using-Deferred-Objects.htm) might be useful. – nrodic Oct 31 '12 at 17:56
  • @Evan, Why should it be handled by jQuery? Suppose I want to fire off a few requests at once without waiting. That's the whole point of such methods being asynchronous. The cool thing with this is you can make a wrapper class to do what you want, if you wish. – Brad Oct 31 '12 at 18:03
  • 1
    if you find what you are looking for post it and mark it as an answer dont edit your question. – Xitcod13 Oct 31 '12 at 18:23
  • I re-read the other topic and my question is actually NOT a duplicate. I was talking about two simultaneous requests for a SAME resource, not two different requests (the code I gave may have mislead you I admit). Otherwise, I agree with @Brad that it would not make much sense. Can someone please reopen the question so I can post the code I came up with ? I have not seen my solution anywhere else and I think it might help a bunch of people. – Louis Ameline Oct 31 '12 at 19:53

0 Answers0