update javascript variable with ajax in real-time

24,757

Solution 1

That is because ajax executes the request asynchronously by default and before the control reaches alert(price); the request has not yet executed and price still holds the old value.

If you want to execute it synchronously then you can set async to false.

$.ajax({
    async: false,
    .....
    .....
});

Solution 2

you need to calculate inside the success function

function calculate_cost(){

var price = 0;
var size = $('form#tshirt_form [name="size"] option:selected').val();
$.ajax({
    url:'my_script.php',
    type:'post',
    data:'query=select price from tshirts.prices where size = "' + size + '"',
    success:function(data){
        if(isjson(data)){
            data = $.parseJSON(data);
            data = data[0];
            price = data['price'];
            //  continue code for calculation
            //  this alert will display "0", but I want the price from the database in there
            alert(price);
           //perhaps do other ajax calls for other bits of data
            //...
        }else{
            //display error getting data
        }
    }
});

// return final_price; this function wont be able to return a value
}

Solution 3

ajax is asynchronous and for this reason you should refactor your code so that you do what you need to do in the callback

$.ajax({
    url:'my_script.php',
    type:'post',
    data:'query=select price from tshirts.prices where size = "' + size + '"',
    success:function(data){
        if(isjson(data)){
            data = $.parseJSON(data);
            data = data[0];
            price = data['price'];
            //call another function (maybe make another ajax call) from here
            dosomethingwithprice(price);
        }else{
            //display error getting data
        }
    }
});

Solution 4

you have to do your calculation inside callback stack. Ajax work async, that means that, codes outsides callback function run before callback function start. So you should do your calculation in callback.

function calculate_cost(){

    var price = 0;
    var size = $('form#tshirt_form [name="size"] option:selected').val();
    $.ajax({
        url:'my_script.php',
        type:'post',
        data:'query=select price from tshirts.prices where size = "' + size + '"',
        success:function(data){
            if(isjson(data)){
                data = $.parseJSON(data);
                data = data[0];
                price = data['price'];
            }else{
                //display error getting data
            }

    //  continue code for calculation
    //  this alert will display "0", but I want the price from the database in there
    alert(price);
    //perhaps do other ajax calls for other bits of data
    //...
         return final_price;
        }
    });

}

Solution 5

Your ajax code takes time to execute (albeit not much); however the code after the ajax call is executed asynchronously, and most likely before the results of the ajax call come in.

Instead, why don't you try moving alert(price) into the body of the if(isjson(data)) region, and then execute a callback function which returns the price to whatever other utility you need it to be used at?

Share:
24,757
jeffery_the_wind
Author by

jeffery_the_wind

Currently a Doctoral student in the Dept. of Math and Stats at Université de Montréal. In the past I have done a lot of full stack development and applied math. Now trying to focus more on the pure math side of things and theory. Always get a lot of help from the Stack Exchange Community! Math interests include optimization and Algebra although in practice I do a lot of machine learning.

Updated on July 09, 2022

Comments

  • jeffery_the_wind
    jeffery_the_wind almost 2 years

    I have a javascript function which needs to do a numerical calculation. Some of the numbers used in this calculation are stored in a database, and they will differ depending on how a user fills out an online form. Once the user fills out the form, they will click the CALCULATE button. At this time, in the JS function, I would like to use ajax to get values from a database that correspond to some other value chosen by the user.

    For a simple example: there are 3 sizes of t-shirts, with different prices based on each size (stored in database). The user chooses the size, and when they click CALCULATE, I use ajax to get the price associated with the size they chose.

    The question is, i want to use ajax to update some variables that I will use later on in the script. The way I am trying to do it now doesn't work, the variable in the script doesn't get updated from ajax, I can only access the value from the database inside the success function of the ajax call. I understand this is because ajax in asynchronous by nature, and it takes some time, waiting for the data to be returned from the server, while the function still continues to run

    In the following example, the ajax call returns JSON data, and I have a function called isjson() that tests if the returned string is in fact JSON data.

    Example code:

    function calculate_cost(){
    
        var price = 0;
        var size = $('form#tshirt_form [name="size"] option:selected').val();
        $.ajax({
            url:'my_script.php',
            type:'post',
            data:'select=price&table=tshirts.prices&where=size = "' + size + '"',
            success:function(data){
                if(isjson(data)){
                    data = $.parseJSON(data);
                    data = data[0];
                    price = data['price'];
                }else{
                    //display error getting data
                }
            }
        });
        //  continue code for calculation
        //  this alert will display "0", but I want the price from the database in there
        alert(price);
        //perhaps do other ajax calls for other bits of data
        //...
        return final_price;
    }
    

    Does anyone know how I can accomplish this, updating variables with ajax in real-time??

    Thanks a lot!

    ** EDIT **

    Thanks everyone for the help, I understand about ajax being asynchronous. I would really like an answer where I don't have to continue the calculation inside the success function, because my actual problem involves many values from quite a few different tables. I would also like to be able to expand on the calculation in the future without it getting too convoluted. If this is not possible, ever, than i will have to live with that. ;-)

    ** EDIT 2 **

    OK, we got the answer: of course it is right near the top on the docs page, :-/ sorry about that. The async property in jQuery ajax call. http://api.jquery.com/jQuery.ajax/