Skip to content Skip to sidebar Skip to footer

How Should I Go About Integrating Ajax?

I have this really messy code in my update.js.erb file which resides in my video directory. It is called every time I add a new comment_title: $('.comments_div').html('<% @video

Solution 1:

You don't really need any javascript for destroy. When you click destroy you can just remove the div. and you won't need to update anything.

Well, actually you do need javascript but not through the controller, this can be done on the client side unless you really need to wait for a response.

Update

This assumes you are using REST.

Ruby array to loop through and identify comment destroy links

<% @video.comment_titles.each do|ct| %>
    <%= link_to "Destroy comment", ct, :method => :delete, :confirm => "Are you sure?", :class => 'destroy' %>
<% end %>

jQuery to process the destroy link:

$(document).ready(function() {
    $('a.destroy').live('click', function(event) {

        if ( confirm("Are you sure you want to delete this comment?") )
            $.ajax({
                url: this.href.replace('/delete', ''),
                type: 'post',
                dataType: 'script',
                data: { '_method': 'delete' },
                success: function() {
                    // the item has been deleted// might want to remove it from the interface// or redirect or reload by setting window.location
                }
            });
        returnfalse;
    });
})

You comment controller:

defdestroy@comment = Comment.find( params[:id] )
    @comment.destroy
    respond_to do|format|
        format.html { redirect_to :back }
        format.js { render :nothing => true }
    endend

Let me know if you get any errors. I'm not quite sure about your routes so It's hard to guess everything.

Post a Comment for "How Should I Go About Integrating Ajax?"