-
-
Save NicholasKirchner/5708171 to your computer and use it in GitHub Desktop.
This file contains hidden or 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() { | |
| $("#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; | |
| }); | |
| }); |
This file contains hidden or 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="/"> | |
| <input type="submit" value="Roll the Die"> | |
| </form> | |
| <div id="die"> | |
| <img src="/1.png" title="" alt="the roll"> | |
| </div> | |
| </div> |
This file contains hidden or 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 | |
| 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