0

I'm importing some data with PHP, which gets data from an SQL database. I'm using AJAX to import the data from the PHP to Javascript. The PHP code works fine and results in "2", but something's wrong with my Javascript code:

<script>
    $.getJSON("Kategorie1.php", function (data) {
        window.nrFragen = JSON.parse(data);
        window.alert(data)
    });
    window.alert(window.nrFragen);
</script>

If I run it, it first runs window.alert(window.nrFragen) which alerts undefined and then window.alert(data), which alerts "2", as it should.

Why does it first run the window.alert(window.nrFragen), even though it's written after window.alert(data)? And, why isn't window.nrFragen = JSON.parse(data); working?

Michael Gaskill
  • 7,913
  • 10
  • 38
  • 43
loelu
  • 85
  • 10

1 Answers1

1

$.getJSON is async.

$.getJSON("Kategorie1.php", function (data) {
    //this will be called only after request completion
    window.nrFragen = JSON.parse(data);
    window.alert(data)
});
//this will be called immediately after $.getJSON, it won't wait for request completion
window.alert(window.nrFragen);
Michael Gaskill
  • 7,913
  • 10
  • 38
  • 43
xZ6a33YaYEfmv
  • 1,816
  • 4
  • 24
  • 43
  • oh ok, thank you. And what can I do to let the program know to wait till the data's here? – loelu Oct 05 '15 at 13:52
  • `$.getJSON`'s second parameter is success handler which will be called when request is successfully completed. So in this callback _data's here_ already. You'd better read [docs](http://api.jquery.com/jquery.getjson/). Also read some articles about asynchronous javascript (or any other language) programming like [this](http://www.html5rocks.com/en/tutorials/async/deferred/). – xZ6a33YaYEfmv Oct 05 '15 at 13:55
  • Not sure if I understand you correctly, I'm gona need the data for the rest of the code, so should I just let the rest of the code run after `window.nrFragen = JSON.parse(data);` – loelu Oct 05 '15 at 13:58
  • yes, all your code that requires the data must be after `window.nrFragen = JSON.parse(data);`. there are other possibilities like [promises](http://www.htmlgoodies.com/beyond/javascript/making-promises-with-jquery-deferred.html) – xZ6a33YaYEfmv Oct 05 '15 at 14:01
  • oh, allright, thank you very much :D – loelu Oct 05 '15 at 14:04