AgostinoX
AgostinoX

Reputation: 7683

rails and javascript, know if the user has confirmed a dialog

In my rails 3.2.17 application, i have a delete button:

<%= link_to 'Delete', destroy_item_path(@item), 
    method: :delete, 
    data: { confirm: "Do you confirm?"},
    id: "a_delete" 
%>

I need to perform some javascript code after the item has been deleted, or better: after the user has confirmed to delete the item.
Naively, i added an id to the anchor and I bound an click listener:

$("#a_delete").click(function() {
    //Has the user confirmed or canceled the operation?
} );

But how can i know what is the user choice? I've checked the https://github.com/rails/prototype-ujs but I didn't figure out how and even if this can be done.

Upvotes: 1

Views: 1515

Answers (3)

fran
fran

Reputation: 326

Click event occurs before the user can cancel or confirm. You could use a form and capture the submit action, which will only happen after the user confirms, and will not happen at all if the user cancels the dialog.

Upvotes: 0

Keith
Keith

Reputation: 696

Instead of having rails.js handle showing the dialog, You can show dialog yourself in your click handler and respond accordingly:

$('#a_delete').click(function(e) {
    if(confirm('Do you confirm?') {
        alert('going to delete!');
    } else {
        e.preventDefault();
        alert('not going to delete!');
    }
} );

This will allow you to do your processing before the delete request is sent to the server.

Upvotes: 1

Alex Tatarnikov
Alex Tatarnikov

Reputation: 353

Easy way(after item will destroyed) it's a send request as JS, rails will render destroy.js.erb and you can add code here. Hard way (after confirm before destroy) it's a modify rails confirmation dialog http://lesseverything.com/blog/archives/2012/07/18/customizing-confirmation-dialog-in-rails/

Upvotes: 1

Related Questions