lundi 29 août 2016

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="" 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  : "",
                type : "POST",
                data : {
                    'id' : id,
                    "_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="">
Cart - <span class="cart-amunt">//display amount here</span> 
<span class="product-count"> //display totalQty here </span>
</a>



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2bO8qrQ
via IFTTT

Aucun commentaire:

Enregistrer un commentaire