Rails destroy confirm with Jquery AJAX
Posted
by Mike
on Stack Overflow
See other posts from Stack Overflow
or by Mike
Published on 2009-08-05T16:48:49Z
Indexed on
2010/04/29
16:37 UTC
Read the original article
Hit count: 258
I have got this working for the most part. My rails link is:
<%= link_to(image_tag('/images/bin.png', :alt => 'Remove'), @business, :class => 'delete', :confirm => 'Are you sure?', :id => 'trash') %>
:class => "delete" is calling an ajax function so that it is deleted and the page isn't refreshed that works great. But because the page doesn't refresh, it is still there. So my id trash is calling this jquery function:
$('[id^=trash]').click(function(){
var row = $(this).closest("tr").get(0);
$(row).hide();
return false;
});
Which is hiding the row of whatever trash icon i clicked on. This also works great. I thought I had it all worked out and then I hit this problem. When you click on my trash can I have this confirm box pop up to ask you if you are sure. Regardless of whether you choose cancel or accept, the jquery fires and it hides the row. It isn't deleted, only hidden till you refresh the page. I tried changing it so that the prompt is done through jquery, but then rails was deleteing the row regardless of what i choose in my prompt because the .destroy function was being called when the prompt was being called.
My question really is how can i get the value to cancel or accept from the rails confirm pop up so that in my jquery I can have an if statement that hides if they click accept and does nothing if they click cancel.
EDIT: Answering Question below. That did not work. I tried changing my link to:
<%= link_to(image_tag('/images/bin.png', :alt => 'Remove'), @business, :class => "delete", :onclick => "trash") %>
and putting this in my jquery
function trash(){
if(confirm("Are you sure?")){
var row = $(this).closest("tr").get(0);
$(row).hide();
return false;
} else {
//they clicked no. } }
But the function was never called. It just deletes it with no prompt and doesn't hide it. But that gave me an idea.
I took the delete function that ajax was calling
$('a.delete').click (function(){
$.post(this.href, {_method:'delete'}, null, "script");
$(row).hide();
});
And modified it implementing your code:
remove :confirm => 'Are you sure?'
$('a.delete').click (function(){
if(confirm("Are you sure?")){
var row = $(this).closest("tr").get(0);
$.post(this.href, {_method:'delete'}, null, "script");
$(row).hide();
return false;
} else {
//they clicked no.
return false;
}
});
Which does the trick.
© Stack Overflow or respective owner