Mihir
Mihir

Reputation: 8734

How to clear the cache for diferred object for below example

I am using following code to retrieve the data from the sharepoint.

RESTQueries.getItemsFromList = function(){
    var deferred = $.Deferred();
    var execute = function(listName,itemId){
        if(typeof(listName)=='undefined' || listName.length==0  ){
            deferred.reject('getItemsFromList - no proper list name');
            return deferred;
        }
        var formatUrl = currentSiteUrl;
        formatUrl = (formatUrl.lastIndexOf('/')==(formatUrl.length-1))?formatUrl:(formatUrl+'/');
        var _url = (typeof(itemId)=='undefined' || itemId=='0')? (formatUrl+"_api/web/lists/getByTitle('"+listName+"')/items") :  (formatUrl+"_api/web/lists/getByTitle('"+listName+"')/items("+itemId+")");
        $.ajax({
            url: _url,
            method:'GET',
            headers:{Accept:'application/json; odata=verbose'},
            success:function(data){
                deferred.resolve(data);
            },
            error:function(err){
                deferred.reject(err.responseJSON.error.message.value);
            }
        });
        return deferred;
    };
    return {
        execute:execute 
    }
}();

To execute this function I am calling this like

RESTQueries.getItemsFromList.execute('Pages').done(function(data){
                        console.log(data);
                    });

This is giving the result without any issues. But the problem is, if I call it for second time for different library like,

RESTQueries.getItemsFromList.execute('Students').done(function(data){
                        console.log(data);
                    });

In this case also result is same as first request. I think some where it is caching the response. How to clear the response for each request?

Upvotes: 1

Views: 55

Answers (2)

Vadim Gremyachev
Vadim Gremyachev

Reputation: 59368

It occurs since the instance

var deferred = $.Deferred();

is created outside of execute function scope. When execute function is called for the second time the done method is getting called for the resolved Deferred object from the previous call.

Solution

Move the declaration of deferred object into the scope of execute function:

var execute = function(listName,itemId){
   var deferred = $.Deferred();
   //...
};

Upvotes: 1

Manvir Singh
Manvir Singh

Reputation: 148

Try including this in your Ajax call:

$.ajax ({
    ...
    cache: false,
    ...
});

Upvotes: 0

Related Questions