A. Apola A. Apola - 4 months ago 20
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:
which are to be displayed on the page. I have been able to return the values in as json:
. Now how do i extract the
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">
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')

var id = $(this).data('id');

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


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;


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>


Try this:

var response = JSON.parse(data);

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

Parse json documentation