0

I am calling JSON data and writing to it as follows:

var data;

$(function () {
    $.getJSON("data.json", function (d) {
        data = d;
    });
    $('.btn').click(function () {
        data['c-type'] = $('#c-ccy option:selected').val();
        data['f-type'] = $('#f-ccy option:selected').val();
        $.ajax({
            type: 'POST',
            url: 'save2json.php',
            data: {'json': JSON.stringify(data)},
            success: function (msg) {
                console.log('php output: ' + msg);
                $.getJSON("data.json", function (d) {
                    console.log('GET JSON:');
                    console.log(d);
                });
            }
        })
    }); // <<THIS BLOCK OF CODE WORKS FINE AND READS/WRITES THE JSON OBJECT data PERFECTLY WHEN .btn IS CLICKED.>>

    console.log(data); // <<ERROR: data undefined>>
})

Could someone please explain why is it that I can't access the data variable in my last line?

revvy
  • 151
  • 3
  • 16
  • `$.getJSON()` is **asynchronous**. Move the `console.log()` call inside the `$.getJSON()` callback. – Pointy Jan 24 '18 at 00:24
  • @Pointy why is it that I can access `data` in the `$.click()` callback? – revvy Jan 24 '18 at 00:28
  • At the point the click event is fired, your original getJSON call has completed. However it hasn't yet completed when you hit console.log. – npearson Jan 24 '18 at 00:35
  • I have a later block of code that runs an `if..else` operation on `data`. Is there a way to access data outside of the `$.getJSON()` callback? – revvy Jan 24 '18 at 00:39
  • Only if it was in an event handler or some other code that would run at a much later time – charlietfl Jan 24 '18 at 00:45

1 Answers1

1

$.getJSON() is asynchronous. That means that you ofte wil call console.log BEFORE java script got the response, hence you don´t have data.