- Use AJAX actions to change views based on asynchronous data
- Implement synchronous / asynchronous requests in a web application
- Enter into an existing code base and extend it
We're going to practice converting a working Sinatra+ActiveRecord app into a Sinatra+ActiveRecord+jQuery+AJAX app. Specifically, we're going to take an application that reloads an entire page every time the user submits a form into one that just updates the portion of the DOM that needs to change.
Release 0: Up and Running
To get started, you should use the application skeleton in
After you download the skeleton, you should
bundle your gems and run
shotgun to see how the app works in its current form:
$ bundle $ bundle exec shotgun
Release 1: Figure Out What to Change
Before you start writing any code, you should fully understand how the existing application works and use that understanding to determine which parts of the code need to change. Specifically:
- What happens when you click the "Roll the Die" button?
- What should happen instead?
- Is it necessary to change any of the ActiveRecord models or migrations?
- Is it necessary to change any of the Sinatra routes?
Release 2: AJAXify It!
The following questions might help you get your bearings:
- How do you intercept a form submission event using jQuery?
- How can we prevent the default form-submission-event action(s) from happening?
- How do we do an AJAX post?
- What should we pass for the
urlargument? How about the
typeargument? (Hint: the HTML
formelement has this for you!)
- How do we pass data to the server when making an AJAX call?
- When the server responds, what code gets run? How do we access the data that the server sends back?
If you cannot answer these questions, you'll have a tough time implementing things. Take your time, use Google, and think it through!