I want to create a confirmation dialog in JavaScript before deleting an item.
My JavaScript code
function confirmerSuppression() {
var confirmation = confirm("Êtes-vous sûr de vouloir supprimer cet élément ?");
if (confirmation) {
window.location.href = '/tiers.destroy/' + id; //
} else {
alert("Suppression annulée !");
}
}
Code for my delete button
<form action="{{route('tiers.destroy', $tiers->id)}}" method="POST">
@csrf
<button onclick="confirmerSuppression()" class="btn btn-danger w-100 type="submit">DELETE</button>
</form>
My route:
Route::post('/tiers/details/{id}', [AppHttpControllerstiersController::class, 'destroy'])->name('tiers.destroy');
My controller :
public function destroy($id)
{
Tier::where("id","=",$id)->delete();
return redirect()->route('prospects.liste')->with("success","Tier supprimée avec succès.");
}
When I click on the DELETE button the dialog appears and when I click on Cancel it deletes the element the same when I click on Yes.
Anyone have an idea please.
2
Answers
It looks like the issue might be related to how you’re constructing the URL for deletion in your JavaScript code. The
id
variable is not defined within theconfirmerSuppression
function.Here’s an updated version of your code:
And in your HTML:
Make sure to pass the
id
from your PHP code to the JavaScript function. Additionally, I adjusted thebutton
type to "button" to prevent the form from being submitted before the confirmation.Also, make sure your route definition in the routes file is using the correct URL structure:
Now, the
id
should be properly passed to theconfirmerSuppression
function, and the URL should be constructed correctly for deletion.You can replace your code with this