title: Laravel 5: how to decode json returned from ajax call
body: <p>I am working on a shopping cart application. when the user clicks the <code>add to cart</code> button, I want the ajax call to my controller function to return two values: <code>totalPrice</code> and <code>totalQty</code> which are to be displayed on the page. I have been able to return the values in as json: <code>{"totalPrice":100,"totalQty":1}</code>. Now how do i extract the <code>totalPrice</code> and <code>totalQty</code> to display on different parts of the page. Thanks.</p>
  
  <p>Here is my code: </p>
  
  <pre><code>&lt;a data-id="{{ $product-&gt;id }}" class="btn btn-success addToCart" &gt;Add to cart&lt;/a&gt;
  </code></pre>
  
  <p>Here is code for my ajax:</p>
  
  <pre><code>    &lt;script type="text/javascript"&gt;
      $(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?
                  }
              });
          });
  
      });
  &lt;/script&gt;
  </code></pre>
  
  <p>Here is my controller method:</p>
  
  <pre><code>public function addToCart(Request $request){
      $post = $request-&gt;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' =&gt; $total_price,'totalQty' =&gt; $total_qty);
      $vals = json_encode($vals);
      echo $vals;
      exit();
  
  }
  </code></pre>
  
  <p>This is where json values returned are supposed to be displayed:</p>
  
  <pre><code>&lt;a href="{{ route('product.shoppingCart') }}"&gt;
  Cart - &lt;span class="cart-amunt"&gt;//display amount here&lt;/span&gt; 
  &lt;span class="product-count"&gt; //display totalQty here &lt;/span&gt;
  &lt;/a&gt;
  </code></pre>