Skip to content

Instantly share code, notes, and snippets.

@michaelchihuyho
Forked from dbc-challenges/lucky_ajax.md
Last active December 19, 2015 22:58
Show Gist options
  • Save michaelchihuyho/6031199 to your computer and use it in GitHub Desktop.
Save michaelchihuyho/6031199 to your computer and use it in GitHub Desktop.

Revisions

  1. michaelchihuyho revised this gist Jul 18, 2013. 1 changed file with 3 additions and 0 deletions.
    3 changes: 3 additions & 0 deletions die.erb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,3 @@
    <% if @roll %>
    <img src="/<%= @roll.value %>.png" title="<%= @roll.value %>" alt="the roll">
    <% end %>
  2. michaelchihuyho revised this gist Jul 18, 2013. 2 changed files with 36 additions and 0 deletions.
    21 changes: 21 additions & 0 deletions application.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,21 @@
    $(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').submit(function(event){
    event.preventDefault();

    // look at form input for debugging
    console.log($(this).serialize());

    // post!
    $.post('/rolls', $(this).serialize(), function(roll_response){
    $('#die').html(roll_response);
    });
    });
    });
    15 changes: 15 additions & 0 deletions index.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,15 @@
    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

    erb :die # HINT: what does this do? what should we do instead?
    end
  3. @dbc-challenges dbc-challenges created this gist Apr 23, 2013.
    5 changes: 5 additions & 0 deletions lucky_ajax.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,5 @@
    # Instructions:

    1. Download this [application skeleton](http://cl.ly/1l1F3N2I3E3x).
    2. Convert the app to use AJAX.
    3. Add any files you changed to your gist and submit your code.