1

I am building a small twitter-like feed. A user has an input, and you have a feed of inputs.

The feed is effectively a list of posts. Each post's view is defined by a _post.html.haml partial view.

I have an AJAX post method that creates a new post in the backend. The problem is that you have to refresh the page to actually view the post appear on the feed.

I would like to append the html to the feed column. However, I create a post on the feed column using a partial view that takes in a local variable of the post details.

Partial views are on the server side. How can I still use the same partial view to obtain the html code for the new post I have created so that I can append it to feed column without having to refresh the page.

Thanks!

2 Answers 2

1

Try render(:update) in the action you post to:

render(:update) do |page|
  page.replace_html 'divID', :partial => 'your-partial'
end
Sign up to request clarification or add additional context in comments.

2 Comments

This couples the frontend to the backend because the frontend depends on the backend knowing about the frontend's structure.
Can this be one in jQuery as well? As from the documentation it was written as prototype helper.
1

Post code snippets so it can easy to answer. Anyway you can do like this. When you are creating a new post using get ajax request it will go into your controller action. In controller action you can do:

   def get_new_post   #This is the controller action called by your ajax
     post = Post.create!(ajax_params)
     render :partial => "post", :locals => {:post => post}
   end

In view you append the new post to post list as below:

$.get("ajax_request", function(data, status){
 if(status=="success"){  //if your ajax is success
   $("#post-list").append(data)  //Assuming post-list is the div id of list of posts
 }
});

5 Comments

how would the render know where exactly to render the partial?
you will get rendered data in data of your ajax request so you can append it to post list
this probably could work (will try it out now). I was wondering if you can you replace the html via the controller as shown by adamdunson? It would mean that I would not have to write up the javascript code as shown. I could not get adamdunson's code to work ...
In adamdunson case might work when you have the partial for list of posts. But when you have partial for displaying single post my solution will work. I think there may be other solutions. But I normally use this one.
anyway you are creating the post using ajax so it will be the get request so response data will contain the your new post when you do render partial

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.