Tim
Tim

Reputation: 541

Good way of avoiding a second ajax call

So I'm doing a an ajax call in this function somewhat like this:

function getCount() {
  $.get("/People/getCount", function (data) {
    if (data && data != "") { 
      // lots of code in here
      }

What I'm doing in another function is making a second call like this:

function worldPeople() {
    return $.get("/People/getCount", function (data) {
     if (data != 0) {
        var target = $("#worldNumbers").find("span");
        target.html(data.length).digits();

     }
  })
}

So I really would like to avoid making that second call. Is there any good way in avoiding that? Maybe do some chaining or such, reusing the callback from the first one? I've heard that its bad practice to do several calls. Regards

Would like to thank all who answered. In the end did not use any of the solutions, I solved it in another way. I'm sure most of the examples you gave me were really good. Do not know how to do with accepting answers. Accept all or none?! Thanks!

Upvotes: 0

Views: 177

Answers (5)

nrabinowitz
nrabinowitz

Reputation: 55678

I generally use a caching module pattern for this kind of thing:

// create a quick singleton to store cached data
var People = (function() {
    // private variable to act as cache
    var count;

    // function to get cached data
    // note: You have to assume it's always asynchronous
    function getCount(callback) {
        // have we loaded the data yet?
        if (count===undefined) {
            // cache miss: load the data, store it, do the callback
            $.get("/People/getCount", function (data) {
                count = data;
                callback(data);
            }
        } else {
            // cache hit - no need to reload
            callback(count);
        }
    }

    // provide access to the getter function
    return {
        getCount: getCount
    };

}());

The first time you hit the cache, it'll load from the server; the second time it will load from the private variable.

// will load the data asynchronously
People.getCount(function(count) {
    alert("First hit: " + count);
});

// will use the cached data
People.getCount(function(count) {
    alert("Second hit: " + count);
});

Depending on the complexity you want to support, you could add additional features like expiring the cache after a particular interval, caching multiple calls (potentially keyed to the AJAX URL), etc. I like to keep the API simple and not reference the AJAX URLs - that way your cache acts like an abstracted service layer, and you can create other cache implementation to work with different data sources - useful for things like stubbing out data before you've implemented your server-side AJAX handlers.

Upvotes: 1

Milan Aleksić
Milan Aleksić

Reputation: 1425

Well, you can just send the function pointer to the function that executes $.get

basically you would then do this:

function worldPeople() {
    getCountFromServer(function(data){
        //do sth with data
    });
}

function getCount() {
    getCountFromServer(function(data){
          //do sth with data
    });
}

function getCountFromServer(callback) {
    return $.get("/People/getCount", function (data) {
        if (data)
            callback(data);
    });
}

Upvotes: 1

Dan
Dan

Reputation: 1888

You can achieve this by handling your Ajax requests using some sort of cache. I use a cache that saves the information retrieved based on the url it called. If another function sets off the same request the cache returns the alraedy fetched data.

What you do need to do as well though is check if the data is outdated so you can refetch it if necessary.

Upvotes: 1

Joe
Joe

Reputation: 82624

You could create a simple data store:

App.store = function () {
    this.people = null;
    this.count
    loadPeople = function () {
         if(this.people === null) {
          $.get("/People/getCount", function (data) {
          if (data != 0) {
               this.count = (data.length).digits();
               this.people = data;
           }
         }
    };
} 

Upvotes: 2

Andrew Orsich
Andrew Orsich

Reputation: 53685

What about store count of peoples in hidden field? And than check this field before sending request.

Upvotes: 1

Related Questions