Wow. This stuff is so cool. I thought Rails was cool enough, but add in some AJAX, jQuery, some Handlebars formatting, and it’s pretty awesome. I likey! So, I’m writing about my second to last project in the Flatiron Online curriculum. It wasn’t a stand alone project; we were building on top of our previous Rails app, just with with a jQuery front end.
The real magic happens when Ajax and jQuery are used together. Ajax allows you to make calls to the database or API behind the scenes, or asynchronously. While jQuery makes it so you can change just what you want on the page (DOM) with the data from your Ajax call. Normally, when a user clicks a button – lets use a comment form, for this example – the following happens:
- The clicked button will take all of the data user filled in on the form (parameters) for a ride to the associated controllers ‘create’ action, which is specified in the form. This will include the comment itself, and the users id.
- The ‘create’ action will try to make a new comment in the database but first it has to pass inspection from the associated model. In this example, we’d go the Comment model.
- If there are any validations for the model, the parameters sent through will have to pass or they will be sent packing and redirecting to the place they came from, with a warning to boot – You must fill in the comment box!
- Assuming they pass, then a new comment will be created in the database and we’ll be redirected to the show page. We’ll call over to the database for the newly created comment by the parameter id sent along from the create action to the show action.
- Now we’re ready for a new page load. The page refreshes and we see our new comment.
That’s quite a lot of work and we have to when the page refreshes, it has to load everything all over again. It would be so much better if the page didn’t refresh and just the newly created comment was appended to it. Can this sort of thing happen? Why, yes Bobby, it can. Enter the world of Ajax and jQuery! In simple terms, jQuery will hijack the submit button request and will handle it a little differently. Let’s check it out!
- Now when our user clicks the submit button on the comment form, jQuery will be listening for this click. Instead of the usual route to the controller action, now the jQuery hijacks the information filled out from the form and we can do what we please with it.
- With the JSON, we can make our Ajax ‘POST’ call. This will basically start the usual process described above, sending our data to the ‘create’ action of the controller and so on.
- When the comment is created, we get the success call back to our Ajax function and we can append the data to the DOM with jQuery.