Skip to content

Instantly share code, notes, and snippets.

@fanda
Created September 26, 2012 20:53
Show Gist options
  • Save fanda/3790522 to your computer and use it in GitHub Desktop.
Save fanda/3790522 to your computer and use it in GitHub Desktop.
Multipage Sinatra Contact Form App with Javascript Client

== Contact form for AJAX requests

Server side is written in Sinatra Client side is written in Javascript with JQuery

You must...

  • include client.js on the client side
  • create #success and #error elements
  • add hidden input field with name "domain" where value matches one case condition in server side script
  • have at least #name, #email and #message input fields
  • add class "req" to required fields for marking invalid inputs Form action is server document root and method is GET
$(document).ready(function() {
$('#contact').submit(function() {
$('#success,#error').hide();
var url = $(this).attr('action')
var params = $(this).serialize()
$.getJSON(url + '?' + params + "&callback=?", function(data) {
if(data == true) { // success
$('#success').fadeIn("slow");
$('#contact')[0].reset();
$('.req').css('border', '');
} else { // error
$('#error').fadeIn("slow");
for (field in data) {
if (data[field])
$('[name^="'+field+'"]').css('border', '1px inset red');
}
}
});
return false;
});
});
require 'rubygems'
require 'bundler'
Bundler.require
require './contact_form'
run Sinatra::Application
Pony.options = {
:via => :smtp,
:via_options => {
:address => 'smtp.sendgrid.net',
:port => '587',
:domain => 'heroku.com',
:user_name => ENV['SENDGRID_USERNAME'],
:password => ENV['SENDGRID_PASSWORD'],
:authentication => :plain,
:enable_starttls_auto => true
}
}
helpers do
def valid_name?(name)
true if name && !name.empty?
end
def valid_email?(email)
email_match = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}/
true if email && !(email =~ email_match).nil?
end
def valid_message?(message)
true if message && !message.empty?
end
def to(domain)
case domain
when 'programatornavolnenoze.cz'
'[email protected]' #'[email protected]'
else
false # do nothing
end
end
end
get '/' do
return jsonp false unless to(params[:domain])
@errors = {}
@failure = false
if !valid_name?(params[:name])
@errors[:name] = true
@failure = true
end
if !valid_email?(params[:email])
@errors[:email] = true
@failure = true
end
if !valid_message?(params[:message])
@errors[:message] = true
@failure = true
end
if @failure
return jsonp @errors
else
Pony.mail(:to => to(params[:domain]),
:from => params[:email],
:subject => params[:subject],
:body => params[:message])
end
return jsonp true
end
source 'http://rubygems.org'
gem "thin"
gem "sinatra"
gem "sinatra-jsonp"
gem "pony"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment