Nikola Ranisavljev
Nikola Ranisavljev

Reputation: 65

Laravel - Ajax and preventdefault

I have a problem with getting items in cart, after I add an item into the cart, Ajax works perfect, then when i try to remove it from the list, first time it wont work with Ajax, if I reload the page it will work.

Ajax generate response like this:

1x ItemTitle X (remove)

When remove has /delete-from-cart/id/place_id

It only works when I reload the page, and also I have a button for coupons that is also managed to work with Ajax, but it only works after refresh.

$('.deletefromcart a').each(function(){
    $('#'+this.id).on('click',function(e) {
      e.preventDefault();
      var id = $(this).attr('data-del');
      var url = $(this).attr('href');
      var place = $(this).attr('data-place');
       $.ajaxSetup({
          headers: {
              'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          }
      });
      $.ajax({
         url: '/delete-from-cart/'+id+'/'+place+'',
         method: 'get',
         data: $(this).serialize(),
         success: function(data){
           toastr.warning('Uspešno ste obrisali iz korpe!', 'Korpa');
             $(".korpa").load(location.href + " #cartAll");
         },
         error: function(data){
           console.log(data);
         }

         });
     });
});

It seems like this function cant find any object to run it from ajax after I add to cart, after refresh it finds.

If you need live preview, i can make you an account.

Upvotes: 1

Views: 407

Answers (1)

Ijas Ameenudeen
Ijas Ameenudeen

Reputation: 9259

You should bind the click event handler on each 'delete' element as,

$('body').on('click', '.deletefromcart a', function (e) {
    e.preventDefault();
    var id = $(this).attr('data-del');
    var url = $(this).attr('href');
    var place = $(this).attr('data-place');

    $.ajax({
        url: '/delete-from-cart/' + id + '/' + place + '',
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        method: 'get',
        data: $(this).serialize(),
        success: function (data) {
            toastr.warning('Uspešno ste obrisali iz korpe!', 'Korpa');
            $(".korpa").load(location.href + " #cartAll");
        },
        error: function (data) {
            console.log(data);
        }
    });
});

Note 1: Your method of binding will attach the event handler to all .deletefromcart a elements. But the one I suggested will bind the event handler to only one element, body. This will also work on dynamically added .deletefromcart a elements.

Note 2: You can include the header values as above too.

Upvotes: 1

Related Questions