Update partial with Ajax in Rails 3

2019-07-16 10:51发布

I have a list of item and a sidebar where I display details about an item. The sidebar is a partial which should change with Ajax when the event onmouseenter is triggered on an item of the list.

I have managed to send the id (of the item on which I enter the mouse) to my controller's action "list" through Ajax but the partial is not updated... :(

I am sure that I am very close to the solution. I am new with Ajax and I have searched the entire afternoon on StackOverflow and many other websites but they always explain how to manage the CRUD actions with Ajax and it doesn't seem to work for me...

Here is the code:

-The ajax part:

$("div.item").mouseenter(function(event){
 var id = $(this).attr('data');
    var url = "/item/list?id="+id+"&lg=en";
    var data = $(this).serialize();
    $.post(url,function(response_data){$("#item_details").html(response_data)});
    return false;
});

-The controller action:

def list
    @items = Item.all
    if request.xhr?
        id_exists?("item", params[:id], "item", "list"){@item = Item.find(params[:id])}

        render :partial => "item/sidebar/sidebar_home", :object => @item
    else
        @item = @items.first unless @items.empty?
    end
end

-The haml:

content_for :sidebar do
   #item_details
       =render :partial => "item/sidebar/sidebar_home", :object => @item


.items_wrapper
-if @items.empty?
    ="No items"
-else
    = render :partial => "item/partials/item", :collection => @items

Inside of the second partial I have the div.item which wraps everything. So basically, I want to update the content of the sidebar, that's all.

Sorry if the question seem silly and thanks in advance for your help.

Problem solved thank to Wizard of Ogz! XD

1条回答
Juvenile、少年°
2楼-- · 2019-07-16 11:31

You need to pass a callback function to handle the response from your AJAX request. See http://api.jquery.com/jQuery.post/

An example could look like this:

$.post(url, data, function(response_data){ $("#sidebar_id").replaceWith(response_data) });
查看更多
登录 后发表回答