开发者

ajax return showing nan

the problem im having is first of all i have a page called ajax.php which with this url ajax.php?id=0001 returns

{"value":250,"price":"5"}

this is the jquery portion

$(document).ready(functi开发者_开发问答on() {


    //field variables

    var quantity = $("#quantity").val();
    var price = $("#pricing p.pps span").text();

    //onload display default data.
    $.get("ajax.php", { id: quantity }, function(data) { $("#pricing p.pps span").html(data.price); }, "json");



    //quantity select
    $("#quantity").change(
    function() 
    { 
        $.get("ajax.php", { id: quantity }, 
            function(data) 
            {
                total = parseInt(price) + parseInt(data.price);
                $("#pricing p.pps span").html(total);       
            }, "json");
    });

});

when the page loads the pricing span gets the value outputted. but when i select the quantity selection the pricing span gets a nan value. can anyone see why?


your price variable is evaluated before any ajax call is made. what is the value of price immediately after this line:

var price = $("#pricing p.pps span").text();

if its not a number then the parseInt(price) call will return NaN

you should set your price var in the callback of the first ajax get:

var price = 0;
$.get("ajax.php", { id: quantity }, function(data) { 
    $("#pricing p.pps span").html(data.price); 
    price = data.price;
}, "json");


There can be two issues with the code. First the price value from the $("#pricing p.pps span").text() line may not be a number so parseInt(price) may return NaN.

Second the data.price coming from the ajax request may not be a valid number so again parseInt(data.price) may return NaN.

The nest way to solve this problem is to keep an alert statement like

alert("price: " + price + ", data.price: " + data.price)

before the line

total = parseInt(price) + parseInt(data.price);

The main problem is the price value is set before the first ajax call that means the price value is an empty string, I think. You have to update the first ajax call as

var price = 0;
$.get("ajax.php", { 
    id: quantity 
}, function(data) { 
    $("#pricing p.pps span").html(data.price); 
    price = parseInt(data.price)
}, "json");

Then you can use it as

total = price + parseInt(data.price);

Another thing to keep in mind is the radix parameter when you work with parstInt() method. It is the number system to be used to parse the string like hexa, octa etc. If you miss this parameter parseInt can return unexpected results if the string starts with a 0 or 0x. link


I think the problem is caused by this part: total = parseInt(price) + parseInt(data.price);

The "price" is undefined in the ajax callback function. You need to define it and give it a value.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜