Knaģis
Knaģis

Reputation: 21475

How to force jQuery to issue GET request to server to refresh cached resource

There are a lot of answers all around the web how to prevent jQuery AJAX requests from being cached. This is not what I'm trying to do.

I need the AJAX request to be returned from the cache based on condition in my code. That is, when the request is issued during page load, it is completely ok to return cached response (in fact that is the intention). But when the user clicks a button, I need the same request to be refreshed from the server.

I know that I can do this by setting cache: false option in jQuery, but this will just request the data with a different URL thus not refreshing the response in the cache and during the next page load the request with cache: true will return the obsolete data.

I tried adding a Cache-Control header to the request but that does not have effect at least in IE10.

$.ajax({
    url: Configuration.ApiRootUri + "Notifications",
    type: "GET",
    headers: { 'Cache-Control': refreshCache ? 'no-cache' : 'private' },
    success: function(data) {}
});

Is it possible at all to force the browser to refresh a cached resource from script?

Upvotes: 3

Views: 919

Answers (1)

Cyril N.
Cyril N.

Reputation: 39859

(note: rewritten after discussion in the comments)

A solution would be to store the response from the server in the localstorage and load it at page load if it does exists.

This avoid completely the request made to the server at start and act like a cache, but in the browser.

Here's a pseudo-algo example :

function loadRequest(){
    Call Ajax request
        On success, store the result in the localstorage, call updateHtml(result);
}

function updateHtml(data) {
    Update the specific html (list, view, etc) with the data
}

$('#mybutton').on ('click', loadRequest);

$(function() {
    Check if the data in the localstorage exists
        if exists, call updateHtml(localstorage.value);
        else call loadRequest 
});

That's it!

Upvotes: 1

Related Questions