mafortis
mafortis

Reputation: 7128

Delete data by ajax in laravel

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.

Upvotes: 1

Views: 147

Answers (1)

aceraven777
aceraven777

Reputation: 4556

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

Upvotes: 1

Related Questions