Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning JSON data using jQuery POST function from server

I am trying to return a json encoded string from PHP script.

$.post("order.php", { product: product_id, coupon: coupon },
function(data) {
    $("#price").html("$" + data.price);
    $("#discount").html("$" + data.discount);
    $("#total").html("$" + data.total);
});

I tried to use alert function in callback to see returning value from PHP:

{"price":249,"discount":"0.00","total":249}

but value of #price and rest elements is "$undefined".

Please help.

like image 325
Aajiz Avatar asked Dec 08 '25 14:12

Aajiz


1 Answers

It seems you just have to parse the JSON data into an object using parseJSON() :

$.post("order.php", { product: product_id, coupon: coupon },
function(data) {
    data = $.parseJSON( data );
    $("#price").html("$" + data.price);
    $("#discount").html("$" + data.discount);
    $("#total").html("$" + data.total);
});
like image 124
Sirko Avatar answered Dec 10 '25 03:12

Sirko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!