Replace Rails favorite feature (Ajax) from jQuery to plain JavaScript

Personal service by Rails realizes the function to add / delete favorites using Ajax.

This embedded Ruby (.js.erb) file for JavaScript for async used jQuery. I used jQuery because it was used in the learning materials around me, including the Rails Tutorial.

However, when I started learning JavaScript firmly these days, I wondered if I could do it with plain JavaScript (Vanila JS) without using jQuery, so I will summarize how to write it in an article.

Please note that this article focuses only on the .js.erb file, so please refer to the Rails Tutorial and the reference article for details on the function itself using Ajax.

Before correction

Since the description contents of app/views/likes/create.js.erb and app/views/likes/destroy.js.erb are the same before and after modification, app/views/likes/create.js Only mention .erb.


var product_id = <%= %> 
$(`#product-${product_id}`).html("<%= escape_javascript(render('likes/like_small_button', product: @product)) %>")

Here's a quick summary of what you're doing with this file.

--Step 1. Substitute @ for product_id --Step 2. Getting the element for # product- $ {product_id} --Step 3. Replace the contents of the element obtained in step 2 with <% = escape_javascript (render ('likes/like_small_button', product: @product))%>

If you break it down a little more, it will be the same as below.


var product_id = <%= %> //step 1
var element = $(`#product-${product_id}`) //Step 2
element.html("<%= escape_javascript(render('likes/like_small_button', product: @product)) %>") //Step 3



We will replace steps 1 to 3 before modification with plain JavaScript.


var product_id = <%= %> //step 1(No change here)
var element = document.getElementById(`product-${product_id}`)
 //Step 2
element.innerHTML = "<%= escape_javascript(render('likes/like_small_button', product: @product)) %>" //Step 3

that's all.

Of course, you can also use the method chain to write:


document.getElementById("product-<%= %>").innerHTML = "<%= escape_javascript(render('likes/like_small_button', product: @product)) %>"


Recommended Posts

Replace Rails favorite feature (Ajax) from jQuery to plain JavaScript
[Rails] Assigning variables from controller to JavaScript
[Rails] Favorite feature
How to implement a like feature in Ajax in Rails
How to deploy jQuery on Rails
How to introduce jQuery in Rails 6
The road from JavaScript to Java
Timeless search with Rails + JavaScript (jQuery)
From pulling docker-image of rails to launching
[Rails] How to convert from erb to haml
Preparing to introduce jQuery to Ruby on Rails
[Rails / JavaScript / Ajax] I tried to create a like function in two ways.