David Morales
David Morales

Reputation: 18064

How to implement an AJAX form and render a template?

I will describe an app that consists of an AJAX form, that also works with Javascript disabled.

When submiting, if Javascript is disabled, it renders a new template called "created". If Javascript is enabled, it should render it as well, but I don't know how to do it.

Please note that the template does not have a controller action nor a route, it is just displayed using the same route as the form.

Files:

app/controllers/users_controller.rb
app/views/users/new.html.erb
app/views/users/created.html.erb

users_controller.rb:

def create
  respond_to do |format|
    format.html { render :created }
    format.js { render js: ??? }
  end
end

new.html.erb:

<%= form_tag users_path, remote: true %>
  <%= email_field_tag :email %>

  <%= submit_tag "OK" %>
<% end %>

created.html.erb:

<div>
  Inside this file there is a big template to be rendered.
</div>

Upvotes: 2

Views: 700

Answers (1)

carpamon
carpamon

Reputation: 6633

You should create a create.js.erb file in views/users and put the content there.

Then just call format.js from de controller.

For a complete example, see this RailsCast: http://railscasts.com/episodes/136-jquery

Upvotes: 1

Related Questions