Before proceeding, please ensure you have implemented CSRF token handling as described in my previous post on passing a CSRF token with an Ajax request in Laravel.
Set Up the Delete Button and Confirmation
<button class="delete-product" data-product-id="{{ $product->id }}">Delete</button>
Step 2: Create the Ajax Request
$(document).on('click', '.delete-product', function() {
var productId = $(this).data('product-id');
var url = '/products/' + productId; // Adjust the URL based on your route and controller setup
if (confirm('Are you sure you want to delete this product?')) {
$.ajax({
url: url,
type: 'DELETE',
data: {
_token: $('meta[name="csrf-token"]').attr('content')
},
success: function(response) {
// Handle the success response (e.g., update UI, display success message)
},
error: function(xhr) {
// Handle errors (e.g., display error message)
}
});
}
});
delete-product
. We retrieve the product ID from the data-product-id
attribute of the button. We then construct the URL for the delete request based on your route and controller setup.DELETE
), and the CSRF token in the request data.