I'm pulling in some JSON and I need that information before the rest of my code runs. I'm very new to jQuery so have been looking at $.when() and setting the AJAX async to be false (which is probably not the best option). I'm also having a problem where my variables are undefined outside of my AJAX call. Here is my code - any help/suggestions would be really appreciated.
//Display nothing while AJAX Call is being made (will add a loading spinner in here)
$('body').css('display','none');
//Ajax call to load images
var test = $.ajax({
dataType: "json",
url: "../quiz/scripts/test.json",
success: function() {
console.log("Loaded in AJAX");
var results = test.responseJSON.Items.Pics;
console.log(results);
$('body').css('display','block');
}
});
// Trying to retrieve my results variable
console.log("Loaded Outside of AJAX");
console.log(results);
Console is giving me this:
Loaded Outside of AJAX [VM] quiz.js (23396):18
Uncaught ReferenceError: results is not defined [VM] quiz.js (23396):19
XHR finished loading: "http://localhost:8888/.....etc"
Loaded in AJAX [VM] quiz.js (23396):9
[Object, Object, Object, Object, Object]
How can I get the text "Loaded in AJAX" to appear before "Loaded Outside of AJAX" and how can I use the variable "results" outside of the AJAX call?
Try this:
If you want to, you can fid some good reference on how a JSON request gets formed in here. I've learned a good bit directly from the API documentation.