Victor Oliveira
Victor Oliveira

Reputation: 1129

How to store information from a ajax request

I have a jquery ajax function with a callback. This callback creates an array from a json that is retrieved from the function. So I have

success: function (response) {
            callback(response);
        },

and the callback creates the array with the call:

Questions(8,createQuestionsArray);

function createQuestionsArray(result){
    for(var subject in result){
        var size =Object.keys(result[subject]).length;
        for(var i=0;i<size;i++){
            questions[i] = result[subject][i];
        }
    }
}

I would like to load this array on the begining of the application so when the user start the quiz I don't need to load the questions. How can I store it? Because just putting in a global questions variable, when I go to another page I have an empty object.

Thanks.

Upvotes: 1

Views: 1778

Answers (1)

stalin
stalin

Reputation: 3464

You can storage on localStorage or sessionStorage, but you should note that both only save string, so you should first stringify the variable

example

for save

var data = JSON.stringify(yourarray);
localStorage.setItem('key',data);

for retrieve

var response = JSON.parse(localStorage.getItem('key'));

see a different between localStorage and sessionStorage

more info about session and local storage-

Upvotes: 3

Related Questions