Created
August 15, 2013 22:02
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// load Ruby on Rails unobtrusive scripting adapter for jQuery | |
// handles AJAX forms and client-side validation | |
//= require jquery_ujs |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ -> | |
# 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 | |
) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.contact.modal.hide.fade | |
.modal-body | |
button.close type="button" data-dismiss="modal" aria-hidden="true" × | |
= 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" × | |
Thanks for your message! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment