Loading data via AJAX is asynchronous. Your first call ($.getJSON
) is executed as soon as the page is loaded, but the callback function that you pass as a parameter, is executed only as soon as the underlying HTTP request is finished. This means that your program does not block to wait for the HTTP request; after calling $.getJSON(...)
your program runs on, and the callback method is called at some time when the HTTP request finished.
You evaluate your data (in your second function) as soon as the page is loaded. But, since your data is loaded asynchronously, it is not yet loaded when the document is rendered and your function is executed.
The solution for your problem would be to move the code that evaluates your data into the callback function of $.getJSON(...)
:
$.getJSON('data.php', function(data) {
if (!data.error) {
// Process your data here!
} else {
alert(data.msg)
}
});