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>';
   }
 }

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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>


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x