Skip to content

Instantly share code, notes, and snippets.

@SmilinColleen
Forked from clay-whitley/application.js
Created September 24, 2013 20:31
Show Gist options
  • Save SmilinColleen/6690776 to your computer and use it in GitHub Desktop.
Save SmilinColleen/6690776 to your computer and use it in GitHub Desktop.
$(document).ready(function() {
$('form').on('submit', function(e){
e.preventDefault();
var formData = $(this).serialize();
// get data from form field
$.post('/grandma', formData, function(response) {
$('#grandma_message').text(response.grandma_response);
});
// create a new ajax request with data
// take response ajax call gives us and perform logic (inserting data we receive back into dom)
});
// This is called after the document has loaded in its entirety
// This guarantees that any elements we bind to will exist on the page
// when we try to bind to them
// See: http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
});
<div class="container">
<h1>Deaf Grandma</h1>
<p id="grandma_message"></p>
<form action="/grandma" method="post">
Say something to Grandma:
<br>
<input type="text" name="user_input">
<input type="submit" value="Say it!">
</form>
</div>
get '/' do
# Look in app/views/index.erb
erb :index
end
post '/grandma' do
content_type :json
if params["user_input"] == params["user_input"].upcase
return {grandma_response: "Not since 1983"}.to_json
elsif params["user_input"] == "I love you."
return {grandma_response: "I love you too! Have a nice day!"}.to_json
else
return {grandma_response: "Speak up, kiddo!"}.to_json
end
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