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

Personal service by Rails supplebox.jp 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.

app/views/likes/create.js.erb


var product_id = <%= @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 @ product.id 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.

app/views/likes/create.js.erb


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

reference

Revised

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

app/views/likes/create.js.erb


var product_id = <%= @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:

app/views/likes/create.js.erb


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

reference

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.