baris1892
baris1892

Reputation: 1051

Ajax request if no cache is available

I'm new to JavaScript/jQuery and I think my problem isn't that hard to solve.

I want to cache a variable (list) in a session and if that list wasn't cached before, an ajax request should be made. My Problem is that globalList is null after the ajax request, so I think I've to wait for finishing the request but I'm not sure how to do this.

var globalList;
function initStuff() {
    globalList = JSON.parse(sessionStorage.getItem('globalList'));
    // if no cached variable is available, get it via ajax request
    if (!globalList) {
        $.getJSON('jsonGetStuff.htm', function (data) {
            sessionStorage.setItem('globalList', JSON.stringify(data));
            globalList = JSON.stringify(data);
        });
    }

    // null, if no cached value is available
    console.log("globalList=" + globalList);

    // TODO: process 'globalList'
}

Upvotes: 1

Views: 248

Answers (2)

num8er
num8er

Reputation: 19372

Your response of request will not be cached when Your url is unique for browser. It's well know practice use it like "your.domain.com/some/uri?{timestamp}".

Try this:

var globalList;
function initStuff() {
    globalList = JSON.parse(sessionStorage.getItem('globalList'));
    // if no cached variable is available, get it via ajax request
    if (!globalList) {
        $.getJSON('jsonGetStuff.htm?' + (new Date()).getTime(), function (data) {
            sessionStorage.setItem('globalList', JSON.stringify(data));
            globalList = JSON.stringify(data);
        });
    }

    // null, if no cached value is available
    console.log("globalList=" + globalList);

    // TODO: process 'globalList'
}

but also jquery has cache: false feature (reference: http://www.w3schools.com/jquery/ajax_ajaxsetup.asp) :

$(function() {
  $.ajaxSetup({ cache: false });
});

but I'm fan of doign it like in first example above.

or some better:

$.ajax({
    cache: false,
    url: "jsonGetStuff.htm",
    method: "GET",
    dataType: "json",
    success: function(data) {
        sessionStorage.setItem('globalList', JSON.stringify(data));
        globalList = JSON.stringify(data);
    }
});

reference: http://api.jquery.com/jquery.ajax/

Upvotes: 1

Avinash
Avinash

Reputation: 6174

Here is the example code for you:

var jqxhr = $.getJSON( "example.json", function() {
  console.log( "success" );
})
  .done(function() {
    console.log( "second success" );
  })
  .fail(function() {
    console.log( "error" );
  })
  .always(function() {
    console.log( "complete" );
  });

// Perform other work here ...

// Set another completion function for the request above
jqxhr.complete(function() {
  console.log( "second complete" );
});

You can make required changes based on your need.

Upvotes: 0

Related Questions