Skip to content

Instantly share code, notes, and snippets.

@angiebui
Forked from dbc-challenges/lucky_ajax.md
Last active December 16, 2015 14:29
$(document).ready(function () {
$("form").on('submit', function(e){
e.preventDefault();
$.ajax({
url: $(this).attr('action'),
method: $(this).attr('method'),
}).done(function(response) {
$("#die").html(response);
});
});
});
<img src="/<%= @roll.value %>.png" title="<%= @roll.value %>" alt="the roll">
<div class="container">
<h1>Simplest Possible AJAX</h1>
<p>This contrived app will simulate a roll of a 6-sided die.</p>
<form method="post" action="/rolls">
<input type="submit" value="Roll the Die">
</form>
<div id="die">
</div>
</div>
get '/' do
erb :index
end
post '/rolls' do
value = params[:value] ? params[:value].to_i : nil
@roll = value ? Roll.create({ value: value }) : Roll.create
erb :die, layout: false #response is what's rendered?
end
# Simple table that represents the roll of a 6-sided die
class Roll < ActiveRecord::Base
attr_accessible :value
validates :value, :inclusion => { :in => (1..6), :message => "must be between 1 and 6" }
after_initialize :roll_if_value_is_nil
private
# If the user passes-in a "value", let's use it. Otherwise, we'll generate a random one.
def roll_if_value_is_nil
self.value = (rand(6) + 1) if not self.value
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment