Skip to content

Instantly share code, notes, and snippets.

@clay-whitley
Forked from dbc-challenges/lucky_ajax.md
Last active December 21, 2015 02:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save clay-whitley/6234158 to your computer and use it in GitHub Desktop.
Save clay-whitley/6234158 to your computer and use it in GitHub Desktop.
$(document).ready(function () {
// PSEUDO-CODE:
// 1- intercept the form submission event using jQuery
// 2- prevent the default action for that event from happening
// 3- generate a random number between 1 and 6 using JavaScript - no it's already done
// 4- use jQuery to submit an AJAX post to the form's action
// 5- when the AJAX post is done, replace the contents of the "#die" DIV in the DOM using jQuery
$('form').on('submit', function(e){
e.preventDefault();
url = $(this).attr('action');
$.post(url, function(json_response) {
// $.post('/rolls', function(json_response) { // this line was originally
//in but was replaced with above to not hardcode in rolls
$('#die').html("<img src="+"'/"+json_response.roll_value+".png' />");
});
});
});
# Set up gems listed in the Gemfile.
# See: http://gembundler.com/bundler_setup.html
# http://stackoverflow.com/questions/7243486/why-do-you-need-require-bundler-setup
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE'])
# Require gems we care about
require 'rubygems'
require 'uri'
require 'pathname'
require 'pg'
require 'active_record'
require 'logger'
require 'sinatra'
require 'erb'
require 'shotgun'
require 'json'
# Some helper constants for path-centric logic
APP_ROOT = Pathname.new(File.expand_path('../../', __FILE__))
APP_NAME = APP_ROOT.basename.to_s
# Set up the controllers and helpers
Dir[APP_ROOT.join('app', 'controllers', '*.rb')].each { |file| require file }
Dir[APP_ROOT.join('app', 'helpers', '*.rb')].each { |file| require file }
# Set up the database and models
require APP_ROOT.join('config', 'database')
source :rubygems
# PostgreSQL driver
gem 'pg'
# Sinatra driver
gem 'sinatra'
gem 'shotgun'
# Use Thin for our web server
gem 'thin'
gem 'activesupport'
gem 'activerecord'
gem 'rake'
gem 'json'
group :test do
gem 'faker'
gem 'rspec'
end
get '/' do
erb :index
end
# TODO: convert this route to use AJAX
post '/rolls' do
content_type :json
# If the user passes-in a "value", let's use it. Otherwise, we'll generate a random one.
# See: roll_if_value_is_nil method in the Roll model.
value = params[:value] ? params[:value].to_i : nil
@roll = value ? Roll.create({ value: value }) : Roll.create
{roll_value: @roll.value}.to_json
end

Instructions:

  1. Download this application skeleton.
  2. Convert the app to use AJAX.
  3. Add any files you changed to your gist and submit your code.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment