javascript - How can I get specific value from returned response

133

I'm trying to create shopping cart with laravel. I have a little problem to update cart items price onchange quantity number input. Ajax sends value and returns in array. But this time the problem is beginning.

This is mycart blade:

 @extends('user.addons.app')
 @push('customCss')
 <link rel="stylesheet" href=" 
   {{asset('/user/assets/css/numberinput.css')}}">
  @endpush
 @section('content')

 @include('user.modules.header')
 @include('user.modules.lsidebar')
 <div id="cart-page-wrapper" class="pt-86 pt-md-56 pt-sm-46 pb-50 pb-md-20 
 pb-sm-10">
  <div >
    <div >
      <div >
        <div >

           @include('user.modules.cart_data')
          <div class="cart-coupon-update-area d-sm-flex justify- 
   content-between align-items-center">
            <div >
              <form action="#" method="post">
                <input type="text" placeholder="Coupon 
      Code"/>
                <button >Apply 
      Button</button>
              </form>
            </div>

            <div >
              <button >Clear 
    Cart</button>
              <button >Update 
    Cart</button>
            </div>
          </div>
        </div>
      </div>
      <div >
        <!-- Cart Calculate Area -->
        @include('user.modules.cartcalculate')
      </div>
    </div>
  </div>
  </div>
 @include('user.modules.footer')
 @endsection
 @push('customJs')

 @endpush

This is mycart_data blade:

 <div >
 <table  >
 <thead>
 <tr>
  <th>Products</th>
  <th>Price</th>
  <th>Quantity</th>
  <th>Total</th>
 </tr>
 </thead>

 <tbody>
 @foreach($carts as $cart)
  <tr>
    <td >
      <div >
        <div >
          <button><i ></i></button>
        </div>
        <a href="single-product-sticky.html" class="product- 
   thumb">
          <img src="{{asset($cart['image'])}}" alt="Product"/>
        </a>
        <a href="single-product-tab-left.html" class="product- 
 name">{{$cart['title']}}</a>
      </div>
    </td>
    <td>
      <span >$ {{$cart['price']}}</span>
    </td>
    <td>
      <input type="hidden" value="{{$cart['id']}}" 
  id="mon{{$cart['id']}}">
      <div >
        <input type="number" min="1" max="9" step="1" value=" 
   {{$cart['quantity']}}" id="qty{{$cart['id']}}">

      </div>

    </td>
    <td>

      <span id="toss{{$cart['id']}}">
      {{$cart['price'] * $cart['quantity']}}
      </span>

    </td>
  </tr>
  @endforeach

  </tbody>
 </table>
 </div>

  <script src="{{asset('/assets/plugins/jquery/jquery.min.js')}}"> 
  </script>
  <script src="{{asset('/user/assets/js/numberinput.js')}}"></script>
 <script>
  @foreach($carts as $cart)
  $("#qty{{$cart['id']}}").change(function(e){
  e.preventDefault();
  var value = $("#qty{{$cart['id']}}").val();
  var id = $("#mon{{$cart['id']}}").val();
  var inputQuantityElement = $("#x{{$cart['id']}}");
  $.ajax({
    type: 'post',
    url: '/cartupdate',
    data: {_token: '{{ csrf_token() }}',value:value, id:id},
    success : function(response) {
      $(inputQuantityElement).val(response);
    }

     });
   });
  @endforeach
  </script>

And this is my function in controller:

public function cartupdate(Request $request)
{
    $cartss = Cart::find($request['id']);
    $quantity = $cartss->quantity;

    if($quantity < $request['value'])
    {
        $update = $cartss->quantity+1;
    }
    else if($quantity > $request['value'])
    {
        $update = $cartss->quantity-1;
    }
    else
    {
        die;
    }

    $cartss->update(['quantity' => $update]);
    $carts = Cart::where('user_id', Auth::user()->id)->get();

    foreach ($carts as $cart)
    {
        $id[] = $cart['id'];
        $pric[] = $cart['price'] * $cart['quantity'];
    }

    return $pric;
}

I want to change dynamicly prices when user clicked quantity input

842

Answer

Solution:

In yourcartupdate() function,return $pric won't give you the result because$pric is declared insideforeach(). Change it to:

$pric = 0;
foreach ($carts as $cart) {
   $pric += $cart['price'] * $cart['quantity'];
}
return $pric;

will give you the total. But, I guess you are trying to get a new price for a particular cart. If so, change yourcartupdate() function to:

public function cardupdate(Request $request) {
   $cart = Cart::find($request['id']);
   $quantity = $cart->quantity;
   if($quantity < $request['value'])
   {
      $quantity++;
   }
   else if($quantity > $request['value']){
      $quantity--;
   }

   $cart->update(['quantity' => $quantity]);

   return $quantity*$cart->price;
}

To update the price in the view, you can use

document.getElementById("toss{{$cart['id']}}").innerHTML = response;

Personally, I suggest you to try Vue.js to build your application. Laravel + Vue.js is a good combination. It much easier to build complex application like this.

Sorry for my bad english :)

People are also looking for solutions to the problem: php - Laravel: When doing an LEFT JOIN how to make alias of fields so I can access fields with the same name

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.