1

I'm trying to delete items by ajax, so far i can get each item id but somehow when i click on delete button it just getting first item id.

code

controller

public function delqtydisc(Request $request,$id)
 {
      $dele = QtyDiscount::find($id)->delete();
      return response()->json($dele);
 }

route

Route::post('/delqtydisc/{id}', 'QtyDiscountController@delqtydisc')->name('delqtydisc');

script

<script>
  $(document).ready(function() {
    $("#addnewqtydiscmsgsave").click(function(e){
      e.preventDefault();
      //this adds new items to database (no issue here)
      $.ajax({
        type: "post",
        url: "{{ url('admin/addnewqtydisc') }}",
        data: {
          '_token': $('input[name=_token]').val(),
          'product_id': $('#product_id').val(),
          'amount': $('#amount').val(),
          'min': $('.min').val(),
          'max': $('.max').val(),
        },
        success: function (data) {
          $('#addnewqtydiscmsg').empty();
          $('#addnewqtydiscmsg').append('<span class="text-success">Discount created successfully.</span>');

          var $tr = $('<tr/>');
          $tr.append($('<td/>').html(data.min));
          $tr.append($('<td/>').html(data.max));
          $tr.append($('<td/>').html(data.amount));

          // This adds delete button to my table
          $tr.append($('<td/>').html("<button class='qtyitemid btn btn-xs btn-danger' data-id='" + data.id + "' type='button'>Delete this</button>"));

          $('.list-order tr:last').before($tr);

          $("#min").val('');
          $("#max").val('');
          $("#amount").val('');

          // From this part delete function adds

          $('.qtyitemid').on('click', function() {
            e.preventDefault();
              var QtyitemID = $('.qtyitemid').data('id');
              console.log(QtyitemID);
              $.ajax({
                  type: 'post',
                  url: '{{ url('admin/delqtydisc') }}/'+encodeURI(QtyitemID),
                  data: {
                      '_token': $('input[name=_token]').val(),
                      'id': QtyitemID
                  },
                  success: function(data) {
                      $('#addnewqtydiscmsg').empty();
                      $('#addnewqtydiscmsg').append('<span class="text-danger">Discount deleted successfully.</span>');
                  }
              });
          });
          // end of delete fuction
        },
        error: function (data) {
            console.log('Error:', data);
        }
      });
    });
  });
</script>

PS: I commented each part of my JavaScript code that I thought should bring your attention // This adds delete button to my table and // From this part delete function adds

Error

when I hit delete button I get 3 results (if i have 3 inputs) in my network, first one return true the other 2 return

"message": "Call to a member function delete() on null",

Any idea?

Update

with code below my problem is solved some how, the only issue is remained is that i still get my row id's multiple. e.g. when i delete id=1 network show it one time but when after that i delete id=2 network shows two times id=2

<script>
  $(document).ready(function() {
    $("#addnewqtydiscmsgsave").click(function(e){
      e.preventDefault();
      $.ajax({
        type: "post",
        url: "{{ url('admin/addnewqtydisc') }}",
        data: {
          '_token': $('input[name=_token]').val(),
          'product_id': $('#product_id').val(),
          'amount': $('#amount').val(),
          'min': $('.min').val(),
          'max': $('.max').val(),
        },
        success: function (data) {
          $('#addnewqtydiscmsg').empty();
          $('#addnewqtydiscmsg').append('<span class="text-success">Discount created successfully.</span>').fadeIn().delay(4000).fadeOut();

          var $tr = $("<tr id='" + data.id + "'>");
          $tr.append($('<td>').html(data.min));
          $tr.append($('<td>').html(data.max));
          $tr.append($('<td>').html(data.amount));
          $tr.append($('<td>').html("<button class='qtyitemid btn btn-xs btn-danger' data-id='" + data.id + "' type='button'>Delete this</button>"));
          $('.list-order tr:last').before($tr);

          $("#min").val('');
          $("#max").val('');
          $("#amount").val('');
          //delete item
          $('.qtyitemid').on('click', function() {
            e.preventDefault();
              var QtyitemID = $(this).data('id');
              console.log(QtyitemID);
              $.ajax({
                  type: 'post',
                  url: '{{ url('admin/delqtydisc') }}/'+encodeURI(QtyitemID),
                  data: {
                      '_token': $('input[name=_token]').val(),
                      'id': QtyitemID
                  },
                  success: function(data) {
                      $('#addnewqtydiscmsg').empty();
                      $('#addnewqtydiscmsg').append('<span class="text-danger">Discount deleted successfully.</span>').fadeIn().delay(3000).fadeOut();
                      $('table tr#'+QtyitemID+'').remove();
                  }
              });
          });
          //
        },
        error: function (data) {
            console.log('Error:', data);
        }
      });
    });
  });
</script>

PS: basically most of my problem is solved i'm just looking for answer to avoid this multiple id in network.

mafortis
  • 6,750
  • 23
  • 130
  • 288
  • You appear to be adding a new set of event handlers every time you click on your `#addnewqtydiscmsgsave` element. Don't do that. Instead, use event delegation. See https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements – Phil Aug 03 '18 at 01:50
  • @mafortis: I think you need to reload the page after deleting an item. Use this in `success: function(data) {`: `location.reload();` Hope it'll fixed your issue!! – Hiren Gohel Aug 03 '18 at 04:46
  • @mafortis: Is that helped?? – Hiren Gohel Aug 03 '18 at 06:07
  • @HirenGohel no bro, i have made some changes base on `aceraven777` answer. it is working now but still i get id of each item twice. (i will update my question) – mafortis Aug 03 '18 at 06:24

1 Answers1

1

The error occurred in your qtyitemid on click event. Specifically this line: var QtyitemID = $('.qtyitemid').data('id'); This JS code will always return the data of the first qtyitemid class. You must use the keyword this to determine what element is clicked. This code hopefully fix the problem:

    $('.qtyitemid').on('click', function() {
            e.preventDefault();
              var QtyitemID = $(this).data('id');
              console.log(QtyitemID);
              $.ajax({
                  type: 'post',
                  url: '{{ url('admin/delqtydisc') }}/'+encodeURI(QtyitemID),
                  data: {
                      '_token': $('input[name=_token]').val(),
                      'id': QtyitemID
                  },
                  success: function(data) {
                      $('#addnewqtydiscmsg').empty();
                      $('#addnewqtydiscmsg').append('<span class="text-danger">Discount deleted successfully.</span>');
                  }
              });
          });
aceraven777
  • 4,358
  • 3
  • 31
  • 55
  • hi, that seem to working (at least getting all my id's) here I share screenshot of the error i'm facing https://ibb.co/fTHkDz – mafortis Aug 03 '18 at 02:24
  • @mafortis, so far I detected 2 problems in your code. 1. After deleting the item you didn't remove the item row from the table, the item still exists on the table so clicking it again will pop an error because its already been deleted. 2. In your controller, before deleting the item, you must first check if the item exists. – aceraven777 Aug 03 '18 at 02:28
  • for issue one i was waiting to fix this issue first, for second issue i think `find()` will do the job of returning item if exist isn't it? – mafortis Aug 03 '18 at 02:29
  • so what do you think the issue is now? – mafortis Aug 03 '18 at 02:31
  • I already told you the 2 problems in your code. You need to fix that. – aceraven777 Aug 03 '18 at 04:05