-1

I want to fetch a String from my DB and put it into my paragraphs:

<p id="q_1"></p>
<p id="q_2"></p>

This here works fine:

$.get("bewertung/get/1", function (data) {
      document.getElementById("q_1").innerHTML = data[0].question;
})

This here doesnt work. Why and how to solve this?

for( var j = 1; j <= 5; j++){
    $.get("bewertung/get/"+j+"", function (data){
         document.getElementById("q_"+j+"").innerHTML = data[0].question;
    })
}
//data[0].question is the field in the DB
Derek Pollard
  • 6,953
  • 6
  • 39
  • 59
Aleks
  • 101
  • 1
  • 12

1 Answers1

1

That is caused by the fact that when you receive a response from the server(or do any other asynchronous operation loop will be done and j variable will be having value 6. To prevent this you need to create closure for asynchronous operations that is being used in for loops. Note that I've used setTimeout instead of AJAX.

for( var j = 1; j <= 5; j++){
    (function(k) {
        setTimeout(function() {
           document.getElementById("q_" + k).innerHTML = 'data';
        });
    })(j);
}
<p id="q_1"></p>
<p id="q_2"></p>
<p id="q_3"></p>
<p id="q_4"></p>
<p id="q_5"></p>
G07cha
  • 4,009
  • 2
  • 22
  • 39