简体   繁体   中英

Laravel delete from Shopping Cart using Ajax

I want to delete from Cart using Ajax, I'm adding with no problem but how can I delete without refresh the page while I have many items and may I need to delete one by one, Im passing the html from delete function in controller to view blade, so when Im at the page for the first time it deletes but after delete of one item cant delete more

 <script>
 $(function(){ 
  $('.remove_item').on("click", function () { 
  var id = $(this).data('id'); 
  $.ajax({
         type: 'DELETE',
         url: "cart/"+ id,  
         data: {'_token': $('input[name=_token]').val()},
         success: function (data) {
           $('#cart_product').html(data);        
         }               
    });
   });
 });
</script>

delete in controller

public function destroy($id)
{
     Cart::remove($id);
     $products = Cart::content();
     foreach($products as $Product){

     echo '<div class="OrderItem_root styles_base styles_spacing-base">
           <div class="OrderItem_quantity styles_just-right styles_base 
           styles_spacing-base">'.$Product->qty.'</div>
           <div class="OrderItem_container">
           <div class="OrderItem_category"></div>
           <div class="OrderItem_itemHeader">
           <div id="titletest" class="OrderItem_name styles_just-right styles_base styles_spacing-base">'.$Product->name.'</div>
           <div id="cartprice" class="OrderItem_total">$'.$Product->price*$Product->qty.'</div>
            <input id="mycartprice" type="text" name="mycartprice" value="'.$Product->price.'"  hidden="">
         </div>
        <div>
        </div>
      <div>
     <button class="remove_item OrderItem_action Button_root" data-id="'.$Product->rowId.'" data-price="'.$Product->price*$Product->qty.'" data-qty="'.$Product->qty.'" type="submit">Remove</button>

     </div>
    </div>
   </div>';
   }
 }

This is because your element is dynamically updated and you should attach event again. use this code instead:

     <script>
     $(function(){ 
 $(document).on('click','.remove_item', function () { 
      var id = $(this).data('id'); 
      $.ajax({
             type: 'DELETE',
             url: "cart/"+ id,  
             data: {'_token': $('input[name=_token]').val()},
             success: function (data) {
               $('#cart_product').html(data);        
             }               
        });
       });
     });
    </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM