0

I have the following JQuery script:

var loaded_data = {};
function data_load(callback) {
    $.getJSON('get_data.php', function (data) {
        $.each(data, function (fieldName, fieldValue) {
            loaded_data[fieldName] = fieldValue;
        });
    });
    callback();
}

function add_data() {
    alert(loaded_data["courses"]);
}

data_load(function () {
    add_data();
});

The function data_load() working properly and loading data. But when I am trying to call add_data() function, I am getting Undefined in alert message. If I am Typing loaded_data["courses"] on console on browser, I am getting desired output.

Browser Console

I don't know loaded_data["courses"] is working properly on Browser console but not on script.

Is There anything like alert() is executing before loading data from get_data.php?

PRATEEK AGRAWAL
  • 319
  • 1
  • 5
  • 17
  • 2
    the misstake is: you call the callback outside the getJSON callback. -> put callback one line up. directly after `$.each`. Explanation: when you call `add_data()` the getJSON is simply not yet finished. – Jeff Feb 21 '18 at 09:11
  • What happens if you use console.log instead of alert in add_data()? – Sondre Sørbye Feb 21 '18 at 09:15

0 Answers0