After the first click to retrieve data(‘product-id’) from delete-btn, I can obtain $product->id and successful deleted.
Next i click to delete another product. It failed and i think it didnt retrieve data(‘product-id’) from delete-btn. Anyone know where is my issue
this is my js code
$(function () {
$("#delete-btn").click(function () {
var productId = $(this).data('product-id');
$('#deleteModal').data('product-id', productId);
});
$('#deleteModal').on('hidden.bs.modal', function () {
$(this).removeData('product-id');
$('#deleteModal').modal('hide');
});
$("#deleteModal .delete-btn-modal").click(function () {
var productId = $('#deleteModal').data('product-id');
$.ajax({
url: '/products/' + productId,
type: 'DELETE',
dataType: 'json',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function (data) {
console.log(data.message);
Swal.fire({
icon: 'success',
title: 'Success!',
text: data.message,
}).then((result) => {
if (result.isConfirmed) {
$('.table').load(location.href + ' .table')
}
});
},
$('#deleteModal').modal('hide');
});
});
My button on index
<button id="delete-btn" type="button" class="btn btn-danger delete-btn inline-block" data-toggle="modal" data-target="#deleteModal" data-product-id="{{ $product->id }}">
Delete
</button>
My modal
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel" aria-hidden="true">
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="deleteModalLabel">Confirm Delete</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>Are you sure you want to delete?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger delete-btn-modal" data-dismiss="modal">Delete</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
2
Answers
You button has same
id
for every product. You should use class insteadbutton has different id for every product. You should use onclick method to call function in jquery.
Try this code i hope this code work for you