A. Apola A. Apola - 3 months ago 15
JSON Question

Laravel 5: how to decode json returned from ajax call

I am working on a shopping cart application. when the user clicks the

add to cart
button, I want the ajax call to my controller function to return two values:
totalPrice
and
totalQty
which are to be displayed on the page. I have been able to return the values in as json:
{"totalPrice":100,"totalQty":1}
. Now how do i extract the
totalPrice
and
totalQty
to display on different parts of the page. Thanks.

Here is my code:

<a data-id="{{ $product->id }}" class="btn btn-success addToCart" >Add to cart</a>


Here is code for my ajax:

<script type="text/javascript">
$(function(){
$.ajaxSetup({
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});

$('.addToCart').click(function(){
var id = $(this).data('id');

$.ajax({
url : "{{ route('product.addToCart') }}",
type : "POST",
data : {
'id' : id,
"_token": "{{ csrf_token() }}"
},
success:function(data){
alert(data); // returns {"totalPrice":100,"totalQty":1}
// how do I decode and display data returned here?
}
});
});

});
</script>


Here is my controller method:

public function addToCart(Request $request){
$post = $request->all();
$id = $post['id'];
$product = Product::find($id);

//some code is excluded to simplify this function

$total_price = 100;
$total_qty = 1;
$vals = array('totalPrice' => $total_price,'totalQty' => $total_qty);
$vals = json_encode($vals);
echo $vals;
exit();

}


This is where json values returned are supposed to be displayed:

<a href="{{ route('product.shoppingCart') }}">
Cart - <span class="cart-amunt">//display amount here</span>
<span class="product-count"> //display totalQty here </span>
</a>

Answer

Try this:

var response = JSON.parse(data);

alert(response.col_name);  // will print the column value

Parse json documentation

Comments