Skip to content

Instantly share code, notes, and snippets.

@NicholasKirchner
Forked from dbc-challenges/lucky_ajax.md
Last active December 18, 2015 01:59
Show Gist options
  • Save NicholasKirchner/5708171 to your computer and use it in GitHub Desktop.
Save NicholasKirchner/5708171 to your computer and use it in GitHub Desktop.
$(document).ready(function() {
$("#die").hide();
$( "form" ).on( "submit", function(event) {
event.preventDefault();
var roll = Math.floor((Math.random()*6)+1);
$.ajax({
type: "POST",
url: '/rolls',
data: roll,
success: function() {
$('#die').find('img').attr('src', "/" + roll + ".png")
$("#die").show();
},
});
return false;
});
});
<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="/">
<input type="submit" value="Roll the Die">
</form>
<div id="die">
<img src="/1.png" title="" alt="the roll">
</div>
</div>
get '/' do
erb :index
end
post '/rolls' do
# If the js 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
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment