Joel Blum
Joel Blum

Reputation: 7878

Rails ajax updating the UI on success

I have a simple posts page where users can create a new post - the form is ajax (and I'm working with turbolinks).

As I see it here are my options:

  1. reload the page with javascript when ajax:success fires

  2. In the Rails controller , return the new post as a json . Then on ajax:success I'll need to somehow create a template

e.g:

$("<div id='new-post'>").html(ajaxResult)
code to append the div to my posts

Upvotes: 0

Views: 251

Answers (2)

anusha
anusha

Reputation: 2135

You can choose option2 that is sending new as js and adding it to the div template using rails

for example:

_form.html.erb

 <%= form_for(@model), :html => {remote: true} do |f| %>
        your input fields code here

 <% end %>

controller.

   def create
    respond_to do |format|
     if @model.save
        format.js
     else
         render 'new'
     end
     end

create.js.erb

$("#get_input").html(<%= j ({render :partial => "create"})%>) **#get_input is your div id**

_create.html.erb

#write your template code here

Upvotes: 1

D.K.
D.K.

Reputation: 446

there are lot's of ways you can do it :)

For ex. you can send not json but js request

def some_action
  respond_to do |format|
    format.html
    format.js
  end
end

then in your /views/../some_action.js.erb

$("<div id='new-post'>").html("<%=j({render here what you want}>")

Or you can really handle json. Then you need to use smth like https://github.com/netzpirat/haml_coffee_assets templates system and easily create js templates based on you JSON

Upvotes: 0

Related Questions