1

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.

Victor Oliveira
  • 1,109
  • 1
  • 12
  • 29
  • Do you have access to the backend file that the ajax call sends data to? – The One and Only ChemistryBlob Sep 23 '16 at 13:54
  • You can use temporary storage or cookie. However, that might be a problem depending on how your application runs. If you expect that some users may look around to cheat the app than is better to load questions from the server on run time. – salih0vicX Sep 23 '16 at 13:55
  • Yes, I have access to the backend. And wouldn't that be the problem I am trying to avoid @salih0vicX? Because I would need to make several calls to the server, right? – Victor Oliveira Sep 23 '16 at 14:00
  • 1
    Yes, you would need several calls to the server but it would be safe way to prevent people from cheating and knowing questions in advance (before they click Start or so). Depending on app front end design those could be simple queries to the server (ajax calls) with a little of traffic. I don't think that should be a problem whatsoever... – salih0vicX Sep 23 '16 at 14:04
  • I see. I will keep this in mind. But I don't think that cheating will be a problem, because it is just playing. So if people cheat that's fine. haha – Victor Oliveira Sep 23 '16 at 14:16
  • In that case I would recommend temporary storage ... or maybe cookie .. In case you find any of our suggestion(s) or answers, please up-vote encouraging us to help even more. Thank you :) – salih0vicX Sep 23 '16 at 14:20

1 Answers1

3

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-

Community
  • 1
  • 1
stalin
  • 3,442
  • 2
  • 25
  • 25
  • I read a little about localstorage when I was doing some researche, I think I am going to try this method and if I find any problem I look for another solution. Thanks stalin. – Victor Oliveira Sep 23 '16 at 14:06