Delete links with confirmation box in Jquery

Submitted by jgoux - 5 years ago

Submit links to a DELETE route with a confirmation box.

// Delete link created in a Presenter or wherever you want (Bootstrap 3 style)
// Generate a CSRF token and put it inside a custom data-delete attribute
public function buttonDelete()
{
    $format = '<a href="%s" data-toggle="tooltip" data-delete="%s" title="%s" class="btn btn-default"><i class="fa fa-trash-o"></i></i></a>';
    $link = URL::route('accounts.groups.delete', ['id' => $this->resource->id]);
    $token = csrf_token();
    $title = "Delete the group";
    return sprintf($format, $link, $token, $title);
}

// Jquery function which listens for click events on elements which have a data-delete attribute
$('[data-delete]').click(function(e){
    e.preventDefault();
    // If the user confirm the delete
    if (confirm('Do you really want to delete the element ?')) {
        // Get the route URL
        var url = $(this).prop('href');
        // Get the token
        var token = $(this).data('delete');
        // Create a form element
        var $form = $('<form/>', {action: url, method: 'post'});
        // Add the DELETE hidden input method
        var $inputMethod = $('<input/>', {type: 'hidden', name: '_method', value: 'delete'});
        // Add the token hidden input
        var $inputToken = $('<input/>', {type: 'hidden', name: '_token', value: token});
        // Append the inputs to the form, hide the form, append the form to the <body>, SUBMIT !
        $form.append($inputMethod, $inputToken).hide().appendTo('body').submit();
    }
});
comments powered by Disqus