Skip to content

Instantly share code, notes, and snippets.

@ejallday
Forked from dbc-challenges/lucky_ajax.md
Last active December 19, 2015 01:38
Show Gist options
  • Select an option

  • Save ejallday/5876939 to your computer and use it in GitHub Desktop.

Select an option

Save ejallday/5876939 to your computer and use it in GitHub Desktop.

Revisions

  1. ejallday revised this gist Jun 27, 2013. 2 changed files with 15 additions and 0 deletions.
    3 changes: 3 additions & 0 deletions _roll.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 %>
    12 changes: 12 additions & 0 deletions index.erb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,12 @@
    <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>

    <div id="die">
    <%= erb :_roll %>
    </div>
    </div>
  2. ejallday revised this gist Jun 27, 2013. 2 changed files with 29 additions and 0 deletions.
    10 changes: 10 additions & 0 deletions application.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,10 @@
    $(document).ready(function () {
    $("form").on("submit", function(event){
    event.preventDefault();
    var rand_num = Math.floor(Math.random() * 6) + 1;
    $.post('/rolls', {value: rand_num}, function(server_response) {
    //var dieRoll = $(server_response).find('#die');
    $('#die').html(server_response);
    })
    })
    });
    19 changes: 19 additions & 0 deletions index.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,19 @@
    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 :_roll, :layout => false # HINT: what does this do? what should we do instead?
    else
    erb :index
    end
    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.