Skip to content

Instantly share code, notes, and snippets.

@Absoludacris06
Forked from dbc-challenges/lucky_ajax.md
Last active December 22, 2015 08:19
Show Gist options
  • Select an option

  • Save Absoludacris06/6444228 to your computer and use it in GitHub Desktop.

Select an option

Save Absoludacris06/6444228 to your computer and use it in GitHub Desktop.
$(document).ready(function () {
var rollThatShit = function(){
return Math.floor(Math.random() * 6) + 1;
};
$('#vegas').submit(function(e){
e.preventDefault();
$.ajax({
url: this.action,
type: this.method,
data: { value: rollThatShit() }
})
.done(function(picture_of_a_die) {
console.log(picture_of_a_die);
$('img').attr('src', '/'+picture_of_a_die.value+'.png');
})
.fail(function() {
console.log("error");
});
});
});
<div class="container">
<h1>Simplest Possible AJAX</h1>
<p>This contrived app will simulate a roll of a 6-sided die.</p>
<form id = "vegas" method="post" action="/rolls">
<input type="submit" value="Roll the Die">
</form>
<div id="die">
<img src=""/>
</div>
</div>
get '/' do
erb :index
end
# TODO: convert this route to use AJAX
post '/rolls' do
# 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.
content_type :json
p params
value = params[:value] ? params[:value].to_i : nil
@roll = value ? Roll.create({ value: value }) : Roll.create
# @roll.value.to_json # HINT: what does this do? what should we do instead?
{: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