Skip to content

Instantly share code, notes, and snippets.

@robvolk
Created August 15, 2013 22:02
Show Gist options
  • Save robvolk/6245384 to your computer and use it in GitHub Desktop.
Save robvolk/6245384 to your computer and use it in GitHub Desktop.
AJAX Forms in Rails => Here are the basic components of building an automagic AJAX form with Ruby on Rails. Rails takes care of the plumbing of submitting the data for you, but leaves the UI logic entirely up to you. Just hook into the Rails' AJAX JavaScript events to control the UI logic.
// load Ruby on Rails unobtrusive scripting adapter for jQuery
// handles AJAX forms and client-side validation
//= require jquery_ujs
$ ->
# contact form
$('.contact.modal form')
.on('ajax:beforeSend', ->
# disable submit button
$('input:submit', $(this)).attr('disabled', true)
)
.on('ajax:success', ->
# show confirmation message
$('.contact.modal .modal-body').toggle()
)
.on('ajax:error', ->
# TODO: handle error
)
class HomeController < ApplicationController
def contact
ContactMailer.contact_us(params[:name], params[:email], params[:message]).deliver
# return a valid response so jquery knows the send was successful
# this can be anything
render :json => { :sent => true}
end
end
.contact.modal.hide.fade
.modal-body
button.close type="button" data-dismiss="modal" aria-hidden="true" &times;
= form_for @model, :remote=>true do
fieldset.fields
.field
= text_field_tag :name, nil, :placeholder=>'Name', :class => 'span3'
.field
= text_field_tag :email, nil, :placeholder=>'Email', :class => 'span3'
.field
= text_area_tag :message, nil, :placeholder=>'Message', :class => 'span3', :rows => '4'
fieldset.actions
= submit_tag 'Send', :class=>"btn btn-primary btn-large"
.modal-body.hide
button.close type="button" data-dismiss="modal" aria-hidden="true" &times;
Thanks for your message!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment