Skip to content

Instantly share code, notes, and snippets.

@Ank13
Forked from dbc-challenges/lucky_ajax.md
Last active December 18, 2015 02:09
Show Gist options
  • Save Ank13/5708962 to your computer and use it in GitHub Desktop.
Save Ank13/5708962 to your computer and use it in GitHub Desktop.
$(document).ready(function () {
$('body').on('click', '#roll_die', function(event) {
event.preventDefault();
var die_number = Math.floor(Math.random()*6 + 1)
var url = $('form').attr('action');
var new_image = '<img src="/' + die_number + '.png" ' + 'title="' + die_number + '" alt="the roll">'
$.post(url, function(data){
$('#die img').remove()
$('#die').append(new_image)
});
});
});
// 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
<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 id="roll_die" type="submit" value="Roll the Die">
</form>
<div id="die">
<% if @roll %>
<img src="/<%= @roll.value %>.png" title="<%= @roll.value %>" alt="the roll">
<% end %>
</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.
value = params[:value] ? params[:value].to_i : nil
@roll = value ? Roll.create({ value: value }) : Roll.create
if request.xhr?
erb :index, :layout => false
else
erb :index
end
# HINT: what does this do? what should we do instead?
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