I'm having a problem filling and accessing a global variable with ajax. I have the following code (stripped down a bit):
var answers;
$(document).ready(function() {
   showResults();
   console.log(answers);
}
function showResults(){
    $.ajax({
        url: "/wp-content/themes/hoekiesikeenschool/question-storage.php",
        data: { action: "get_results" },
        type: "post",
        dataType: "json"
    }).done(function (data) {
        answers = data.questionary; 
        return answers;
    }); 
}
My question is the following: When I log answers in the done function it gives me a nice array. That would mean the array variable is filled. But when I log it from $(document).ready, It returns an empty variable. This is probably because the AJAX call is asynchronous, and the log gets executed before the variable is filled.
However, I need to use that variable on another page, so I need to access it from the $(document).ready ... Any idea about how to check if the variable is filled? Or when the showResults() is completed? Thanks in advance for your help!
- Edit -
Thanks for your replies! But I'm still struggling with the following: As I understand, I can call another function from the ajax callback, and pass it the data. The thing is, I have to do a lot of different stuff with it after the call, and the only way I can get it to work now is by calling a function in the ajax callback, then calling another one from that one, etc...
So I end up wit showResults(); in the doc.ready, which then executes a lot of functions that are all "linked" together. Is there anyway I can return the data to the variable, for use in other places? I hope I have made this clear, English is not my native language, sorry.
 
     
     
     
     
     
    