0

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>
1
  • try JSON.parse(data); Commented Aug 30, 2016 at 6:53

5 Answers 5

3

Try this:

var response = JSON.parse(data);

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

Parse json documentation

Sign up to request clarification or add additional context in comments.

Comments

2

when you use ajax method for send and receive , you better using from datatype

if using dataType:'json', , This problem was solved .

and you can using in success :

success:function(data){
  alert(data.totalPrice); 
}

Comments

2

If you are returning encoded json data from Laravel then in jQuery you can use dataType:'json' while making ajax request and it will convert response data to json itself, you don't need to convert to JSON manually, jQuery will do it for you.

$.ajax({
    ...
    dataType:"json",
    data : {
        'id' : id,
        "_token": "{{ csrf_token() }}"
    },
    ...
});

see http://api.jquery.com/jquery.ajax/ for full list of values that you can use in dataType.

Comments

1

Have a look at Laravel's json response. If you merely echo it out in your controller, it will be returned as string, if you return it as a json response. You can just refer it as data.totalPrice in your javascript.

Thus you can do something like this:

 success:function(data){
               $(".product-count").html(data.totalQty);
 }

Comments

1

You can use JSON.parse() in case you are json_encode() encoding in the controller. If you dont do json_encode() in the controller then you can access response values without JSON.parse()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.