Sharing the Code

Programming stuff that might be useful to others

A basic ajax form in Rails

This basic example shows you how you can submit a form without having to refresh the page. This might be useful, for example, when you want to do inline editing. The following example allows you to update the name of an item without affecting anything else that might be on the page.

In the view the form is rendered as a partial inside a div. When the form is submitted the contents of the div are replaced with what the web app returns which is the form again but it might include an error message.

[sourcecode language=”html”]

<%= render 'edit_name' %>


Below is the form itself, in the partial. The only difference to a standard form is that remote is set to true on form_for.

[sourcecode language=”html”]
<%= form_for @item, remote:true do |f| %>
<% if @error %>

<%= @error %>

<% end %>

<%= f.text_field :name %>
<%= f.submit 'Update' %>

<% end %>

The controller updates the model in the standard way but instead of returning HTML it returns Javascript.

[sourcecode language=”ruby”]
class ItemsController < ApplicationController def update @item=Item.find(params[:id]) respond_to do |format| if !@item.update_attributes(params[:item]) @error='Could not update name' end format.js end end end [/sourcecode] The Javascript basically replaces the contents of the div with the form partial. The view helper j escapes the HTML so it can be passed as a string to the JQuery method html. This piece of generated Javascript is passed back to the browser in the response and the browser just executes it. app/views/items/update.js.erb: [sourcecode language="javascript"] $('#edit_name').html("<%= j render 'edit_name' %>“);

Comments are closed