loelu loelu - 6 months ago 9
JSON Question

What's wrong with my JSON.parse and why's the code not executed in order of appearance?

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?

Answer

$.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);
Comments