-
-
Save nathanallen/6445418 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div id="die"> | |
<% if @roll %> | |
<img src="/<%= @roll.value %>.png" title="<%= @roll.value %>" alt="the roll"> | |
<% end %> | |
</div> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(document).ready(function () { | |
$('form').on('submit', function(event){ // 1- intercept the form submission event using jQuery | |
event.preventDefault(); // 2- prevent the default action for that event from happening | |
var roll = Math.floor((Math.random()*6)+1); // 3- generate a random number between 1 and 6 using JavaScript | |
$.ajax({ | |
url: this.action, | |
type: this.method, // 4- use jQuery to submit an AJAX post to the form's action | |
data: roll | |
}).done(function(){ | |
$('#die').html("<img src='" + roll + ".png'>") // 5- when the AJAX post is done, replace the contents of the "#die" DIV in the DOM using jQuery | |
}).fail(function(){ | |
console.log("fail"); | |
}) | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
get '/' do | |
erb :index | |
end | |
# TODO: convert this route to use AJAX | |
post '/rolls' do | |
# p params | |
# # 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 | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment