admin管理员组

文章数量:1192529

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. .ajax/

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/

Share Improve this question edited Apr 2, 2012 at 15:00 jeffery_the_wind asked Apr 2, 2012 at 14:42 jeffery_the_windjeffery_the_wind 18.2k35 gold badges106 silver badges165 bronze badges 6
  • 5 data:'query=select price from tshirts.prices where size = "' + size + '"', Please don't do that. What if data:'query=drop table users' – karim79 Commented Apr 2, 2012 at 14:44
  • 2 I sure hope you do some mega-clever input sanitation from the data: query= part – bububaba Commented Apr 2, 2012 at 14:45
  • wow thanks, yes i that could be catastrophic – jeffery_the_wind Commented Apr 2, 2012 at 14:48
  • 1 It looks like you're making it very easy for someone to run a SQL injection attack. Your server-side code is going to execute any query that is thrown at it. It would be better to store the SQL statement in the PHP code and just pass the size parameter. – Josh Siok Commented Apr 2, 2012 at 14:50
  • Right, I got that now, thanks! – jeffery_the_wind Commented Apr 2, 2012 at 14:52
 |  Show 1 more comment

6 Answers 6

Reset to default 14

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,
    .....
    .....
});

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
}

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
        }
    }
});

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?

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;
        }
    });

}

I suggest having the ajax call return a deferred object. Then, when the final price is completely calculated, resolve the deferred object with that value.

function calculate_cost() {
    var price = 0,
        size = $('#tshirt_form [name="size"] option:selected').val(),
        def = $.Deferred();

    $.ajax({
        data: {size:size},
        url: 'my_script.php',
        type: 'post',
        dataType: 'json',
    }).done(function(data){
        data = data[0];
        price = data['price'];
        def.resolve(price);
    }).fail(function(){
        // do on error stuff
    });

    return def.promise();
}
// ...
calculate_cost("large").done(function(price){
    alert(price);
}).fail(function(){
    alert("Failed to retrieve price");
});

本文标签: jqueryupdate javascript variable with ajax in realtimeStack Overflow