0

while loading some HTML by code I want to get some data from the server. So I start with a synchronous function and within this I call a POST.

I created a example

$(document).ready(function() {

  for (var i = 1; i < 6; i++) {
    var div = $("<div></div>");

    var price = 0;
    
    /* get the price from the server by passing the object id

    $.ajax({
      type: 'POST',
      url: '/getPrice',
      contentType: 'application/json',
      data: JSON.stringify({
        id: i
      })
    }).done(function(response) {
      price = response.price;
    });
    
    */

    div.html("id " + i + " price " + price);

    $("#container").append(div);
  }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="container">
</div>

When running the code the price is always 0. I know the AJAX call is asynchronous but how can I fix the code?

peterHasemann
  • 1,550
  • 4
  • 24
  • 56

1 Answers1

1

put your code inside done like

$.ajax({
  type: 'POST',
  url: '/getPrice',
  contentType: 'application/json',
  data: JSON.stringify({
    id: i
  })
}).done(function(response) {
  price = response.price;
  div.html("id " + i + " price " + price);
  $("#container").append(div);
});
Aswin Ramesh
  • 1,654
  • 1
  • 13
  • 13