Creating an Ajax-based cart

Working with AJAX

Ajax lets us write code that runs in the browser and interacts with our server-based application. In our case, we’d like to make the “Add to Cart” buttons invoke the server create action on the LineItems controller in the background. The server can then send down just the HTML for the cart, and we can replace the cart in the sidebar with the server’s updates.

Normally, we’d do this by writing JavaScript that runs in the browser and server-side code that communicates with this JavaScript (possibly using technology such as JavaScript Object Notation [JSON]). The good news is that, with Rails, all this is hidden from us. We can use Ruby to do everything we need to do with the added benefit of support from some Rails helper methods.

The trick when adding Ajax to an application is to take small steps, so let’s start with the most basic one. Let’s change the catalog page to send an Ajax request to our server application and have the application respond with the HTML fragment containing the updated cart.

On the index page, we’re using button_to() in line 19, to create the link to the create action. We want to change this to send an Ajax request instead. To do this, we add a remote: true parameter to the call in line 20:

Get hands-on with 1200+ tech skills courses.