user3651999
user3651999

Reputation: 113

How to prevent refetching AJAX data?

I'm using javascript but not jQuery.

Let's say I have 3 users in my database [Kim,Ted,Box] and 3 buttons as below:

<button class="user">Kim</button>
<button class="user">Ted</button>
<button class="user">Box</button>
<div id="displayArea"></div>

If a person clicks on any of the buttons it will display the user information in the div.

Assume I click on the Kim button and it uses ajax and displays the information of Kim. And now I click Ted it also calls a new ajax function to get the data. But when I click Kim again I call the new ajax function to get the data rather than get the data from cache or some place. How can I achieve it without getting the data from ajax function if the data is loaded before?

The reason why I need this is because I don't want the user to wait to get the data again that they loaded before.

Upvotes: 1

Views: 55

Answers (1)

Felix Kling
Felix Kling

Reputation: 816960

Add one level of abstraction by creating a function that takes care of the caching and either returns the data from the cache or makes an Ajax request. For example:

var getDataForUser = (function() {
    /**
     * We use an object as cache. The user names will be keys.
     * This variable can't be accessed outside of this function
     */
    var cache = {}; 

    /**
     * The function that actually fetches the data
     */
    return function getDataForUser(user, callback) {
        if (cache.hasOwnProperty(user)) { // cache hit
            callback(cache[user]);
        } else {
            // somehow build the URL including the user name
            var url = ...;
            makeAjaxRequest(url, function(data) { // cache miss
                cache[user] = data; // store in cache
                callback(data);
            });
        }
     };
}());

Then you make the call

getDataForUser('John', function(data) { /*...*/ });

twice and the second time it will hit the cache.

Upvotes: 1

Related Questions