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
- In your product module, create a delete button for each product item in your HTML markup. Assign a unique identifier to each delete button (e.g., using the product ID).
<button class="delete-product" data-product-id="{{ $product->id }}">Delete</button>
- Additionally, set up a confirmation dialogue to confirm the deletion. This step helps prevent accidental deletions.
Step 2: Create the Ajax Request
- In your JavaScript code, listen for the click event on the delete button and initiate 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)
}
});
}
});
- In the example above, we listen for a click event on any element with the class
delete-product
. We retrieve the product ID from thedata-product-id
attribute of the button. We then construct the URL for the delete request based on your route and controller setup. - Inside the Ajax request, we specify the URL, HTTP method (
DELETE
), and the CSRF token in the request data. - Adjust the success and error callbacks according to your needs. You can update the UI, display messages, or perform any other necessary actions.