Skip to content

Instantly share code, notes, and snippets.

@avanishgiri
Forked from dbc-challenges/lucky_ajax.md
Last active December 17, 2015 08:38
Show Gist options
  • Save avanishgiri/5581065 to your computer and use it in GitHub Desktop.
Save avanishgiri/5581065 to your computer and use it in GitHub Desktop.
$(document).ready(function () {
$('form').submit(function(e){
e.preventDefault();
$.ajax({
type: 'post',
data: $(this).serialize(),
url: '/rolls'
}).done(function(response){
$('div #die').replaceWith(response);
});
});
});
<div id="die">
<% if @roll %>
<img src="/<%= @roll.value %>.png" title="<%= @roll.value %>" alt="the roll">
<% end %>
</div>
<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>
<%= erb :die %>
</div>
get '/' do
erb :index
end
# TODO: convert this route to use AJAX
post '/rolls' do
p request
# 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
erb :die, :layout => false # HINT: what does this do? what should we do instead?
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment