Skip to content

Instantly share code, notes, and snippets.

@torsday
Forked from dbc-challenges/lucky_ajax.md
Last active December 16, 2015 14:20
Show Gist options
  • Select an option

  • Save torsday/5448388 to your computer and use it in GitHub Desktop.

Select an option

Save torsday/5448388 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
// 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();
console.log($(this).serialize())
$.ajax({
type: "POST",
url: $(this).attr('action'),
data:$(this).serialize()
}).done(function(data){
$('#die').html("<img src='/"+data+".png' title='"+data+"' alt='the roll'></img>")
}).fail(function(){console.log("failed")})
});
});
<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">
Cheater: <input type="text" name="value"></input></br>
<input type="submit" value="Roll the Die">
</form>
<div id="die">
</div>
</div>
get '/' do
erb :index
end
post '/rolls' do
return 500 unless (((1..6).include? params["value"].to_i) || (params["value"] == ""))
value = params["value"] != "" ? params["value"].to_i : nil
@roll = value ? Roll.create({ value: value }) : Roll.create
@roll.value.to_s
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