Reputation: 23405
I have a gallery of elements, each with a class of "#thumbnail", each thumbnail has a "delete" link below it.
The problem with the code below is that the JavaScript "ajax:success" code only runs upon the first click i.e. it invokes the alert dialog, each time I subsequently click on another "delete" link the ajax fires & the action in my controller does what I expect, however the alert dialog is never shown again - unless I refresh the entire page & then of course it only works the first time again.
Can anyone see what is going wrong? I have searched for an answer here but to be honest am a little lost.
link_to (view):
<%= link_to("Delete", "/graphics/0?url=#{image_url}", :method => "delete", :remote => true, :id => "delete-graphic") %>
Controller action:
def destroy
render :json => {"result" => "ok"}
end
JS:
$(document).ready(function() {
$('#delete-graphic').bind('ajax:success', function() {
alert("delete");
});
});
Upvotes: 1
Views: 541
Reputation: 5714
DOM IDs are intended to be unique. You should bind to a class rather than an ID, this will enable your jQuery method to work on every call rather than just on the first one.
Change your link_to
call to use a class:
<%= link_to("Delete", "/graphics/0?url=#{image_url}", :method => "delete", :remote => true, :class => "delete-graphic") %>
Change your jQuery to bind to the class:
$(document).ready(function() {
$('.delete-graphic').bind('ajax:success', function() {
alert("delete");
});
});
Upvotes: 1