2

I thought I had this mess sorted out in my head but for some odd reason its not working.

If you declare a variable outside of a function / scope and refer to it without the var inside a function then it changes the variable declared previously... right?

however, the first alert returns the correct price, but the second (last) alert returns 0. What am I doing wrong?

//get pricing
var price=0;
var modelid = $("#model_input").val();
var inCode = $("#code_input").val();
$.get("getpricing.php", {  'modelid': modelid ,'code' : inCode }, function(data){
    price = data;
    alert(price);
});
alert(price);
rideon88
  • 298
  • 2
  • 12
  • Are you defining a price variable within the function fed to $.get? – meder omuraliev Aug 14 '09 at 04:54
  • @meder: the callback function is right there in the code... no there is no extra declaration – Luke Schafer Aug 14 '09 at 04:56
  • 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 Dec 14 '20 at 20:30

2 Answers2

8

You are using an Ajax request.

Those, unkess specified otherwise, are Asynchrounous : they are executed in the background, without stopping the execution of the rest of the script.

So, the alert on the last line of code is executed before the Ajax request is finished ; which means price is still 0 at that time.

One way to change that would be to use a synchronous request (see async option) ; but I strongly advise against it ; quoting the doc :

By default, all requests are sent asynchronous (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.

And you definitly don't want your application to freeze the whole browser!

You should re-think the way your application is designed, in this case : you can only use the "price" information after the Ajax request is finished -- which probably means you should place more code inside the function called on its success : just placing code after the $.get is not enough.

Pascal MARTIN
  • 395,085
  • 80
  • 655
  • 663
3

httprequests using .get are asynchronous, so the first alert (the second declared) will alert the original value as the callback for the request has not triggered yet.

Luke Schafer
  • 9,209
  • 2
  • 28
  • 29
  • Weird. I'm not actually using the price variable until an If and a For loop later (basically a ton of lines down). But by then, it still hasn't made the call I assume. If I just change to post will it work as expected? – rideon88 Aug 14 '09 at 04:59
  • No. post and gets are still asynchronous – Luke Schafer Aug 14 '09 at 05:05