0

Sorry first for my bad english.

I have a DIV with an ID, which I let fill with a table.

In JavaScript / jQuery I have a For loop which defines the content of the table. So far it works, but for some unknown reason I can't access the JSON output. I would be very grateful for a hint what is wrong.

<div id="output"></div>

<script>
var urlParams = new URLSearchParams(window.location.search);
var split = urlParams.get('query').split(',');
var output = "<table id='table'>";

    for(var i=0;i <split.length;i++){
        $.getJSON("http://example.com/?query=" + split[i] + "", function(JSONOut) {
            var JSONoutput[i] = JSONOut.id
        });
        
        var output = output + "<tr class='z'>";
        var output = output + "<td><div class='ausgabe1'>" + split[i] + "</div></td>";
        var output = output + "<td><div class='ausgabe1'>" + JSONoutput[i] + "</div></td>";
        var output = output + "</tr>";
        
    }
}
var output = output + "</table>";

$('#output').html(output );
</script>
  • What do you mean when you say you can't access it? Can you observe the requests and are they being made? – Grigor Sep 22 '20 at 21:00
  • 2
    Does this answer your question? [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Heretic Monkey Sep 22 '20 at 21:00
  • In this case, you're declaring the variable inside the scope of the callback function, so you can't access it from the outer scope. You also can't declare an indexed variable like that. – Heretic Monkey Sep 22 '20 at 21:02
  • Like @HereticMonkey mentioned, you're likely running into an issue with async calls. Since `getJSON` is non-blocking, you have to wait for it to finish. Take a look at this: https://stackoverflow.com/q/2765411/854698 – Grigor Sep 22 '20 at 21:02
  • @Grigor The answer is **not** to use the deprecated `async: false` flag in jQuery's ajax implementation. The answer is to either create a closure over the variables involved, or to create an array of `$.getJSON` calls and use `$.when` to get an array of the results. – Heretic Monkey Sep 22 '20 at 21:06
  • @HereticMonkey good to know. – Grigor Sep 22 '20 at 23:46

0 Answers0