0

Trying to get data from JSON when a button is pressed and for some reason I'm getting an error the first time the button is pressed and then if you hit it again I get the popup but with the id that was pressed the first time. i understand what it is doing but I don't know why.

Data:

 id: 1, price: 5.00;
 id: 2, price: 9.30;

Script:

function updateStock(id){

$.ajax({
    url: 'json.watching.php?id=' + id,
    dataType: 'json',
    cache: false,
    success: function(data) {
        price = data.price;
    }
});

    $('#dialog-popup').html("<div align='center'>id: " + id + ". Price: " + price + "</div>");
    $("#dialog-popup").dialog("open");
}

Buttons:

<button onclick="updateStock(1)" style="button">Button 1</button>
<button onclick="updateStock(2)" style="button">Button 2</button>

The first time the button is pressed I get the Uncaught ReferenceError: price is not defined but if I press it again I get the data but from the id of the button press before it. So if load the page and press the first button I get the error, if I press the same button I get the popup with the correct price, but I if I hit the second button my popup responds with "id: 2. Price: 5.00". The id is correct but the ajax data is from the previous button press and doesn't update the variables.

Chad Priddle
  • 650
  • 2
  • 15
  • 32

1 Answers1

0

Ajax is asyncbronous, so you are reading the value before it si set. Move the dialog call to inside the success call.

function updateStock(id){
  $.ajax({
    url: 'json.watching.php?id=' + id,
    dataType: 'json',
    cache: false,
    success: function(data) {
        price = data.price;
        $('#dialog-popup').html("<div align='center'>id: " + id + ". Price: " + price + "</div>");
        $("#dialog-popup").dialog("open");
    }
  });
}
epascarello
  • 204,599
  • 20
  • 195
  • 236