0

I have a totalPrice variable in JavaScript:

var totalPrice = 0;

With AJAX, I send a request to a server and I get my result from it, and I want the server result to be assigned to totalPrice:

$.request('onGetProductId', {
    data: { productId: productValue },
    success: function (data) {
        totalPrice = data.result;
    }
});
alert(totalPrice) // This line i want to get server's response but i get zero.

When I call totalPrice out of AJAX I get 0 value but I want to get value in data.result. How can i fix it?

Farzin Bidokhti
  • 71
  • 1
  • 10
  • Well it depends on where the `var totalPrice = 0;` is relative to your AJAX code, please paste more relevant code so we can understand where the problem is exactly. – M0nst3R Jun 30 '20 at 10:23
  • I think you are getting the value of `totalPrice` right after the `ajax request`. You need to wait until the get the response and `totalPrice` get updated. Because `ajax requests` are `asynchronous`. – BadPiggie Jun 30 '20 at 10:24
  • @GhassenLouhaichi , I want access to totalPrice after ajax request call and i set totalprice value with server's response. when i call totalPrice after Ajax request i get zero value but i want to get the server's response, i edite my code please see again. – Farzin Bidokhti Jun 30 '20 at 10:33
  • "*How can i fix it?*" - move the `alert` (or anything that uses the `totalPrice`) inside the success callback. – Bergi Jun 30 '20 at 10:40

1 Answers1

1

short answer: you can't. your AJAX call is asynchronous, which means the success function executes god knows when.

The code you have written below it in your script can't access that fragment of code, because it is likely to be executed before the ajax call is resolved.

If you want to alter the DOM with the result you get from your ajax call, you need to do it in the success function. If you absolutely need to reuse that value elsewhere in your code, you can just grab it from the DOM, but I would advise caution.

Arthur Boucher
  • 307
  • 1
  • 7