Is it possible to update a Rails element using an AJAX request?

I've delved into a plethora of information regarding Rails, AJAX, and 5.1 Unobtrusive Javascript. It provides insight on how to handle AJAX calls in Rails with a .js file, for example.

However, my goal isn't to serve up an entire .js file; rather, I aim to update an element after a <% link_to %> POST request. As far as I understand, setting remote: true submits it as an AJAX request.

Essentially, I have a "Post" that users can like by clicking a Like button. This triggers a POST request to the "Post" controller, which then updates the post as liked and adds a like to it.

Unfortunately, to witness the effects of liking the post (which simply changes the color of the link and the font-awesome icon), one must refresh the page. My aim is to have these updates occur without requiring a page refresh.

After some research, I believe I need to use respond do and respond via a .js file to properly handle the request with a given view to be updated (for instance, if the controller action is named "like", maybe a like.js.erb file would be used for updating?). However, I wish to avoid serving an entirely new page or only run the .js file?

Subsequently, I could potentially utilize something like

$('i.fa-icon#id').style.color = "blue"
or similar? (I assume data can be transmitted from the controller to the .js.erb file?). I am uncertain about the best approach for this, as Rails elements often feature some sort of data-attribute or something akin to that (given my status as a beginner).

Answer №1

Indeed, your explanation is spot on! Contrary to the previous response, an event listener is not necessary. However, if you prefer having a respond_to in the controller, then you can start with the following HTML snippet:

# post/index.html.erb
<div id="like-button">
  <%= button_to "Like this post", post_path(@post), remote: true %>
</div>

Remember that using the button_to helper will automatically create a POST request.

When this button is clicked, it will trigger the controller#update, which should be updated as follows:

#posts_controller.rb
...
def update
  @post.save
    respond_to do |format|
      format.html { redirect_to post_path(@post) } 
      format.js  # <-- will render `app/views/posts/update.js.erb`
    end
end

Note: If JavaScript is disabled, the format.html will be rendered. However, with JS enabled, the app/views/posts/update.js.erb file will execute. Here's an example of its content:

const likeButton = document.getElementById('like-button');
likeButton.innerHTML = '<%= j render "posts/liked-link", post: @post %>';

The last line replaces the inner HTML of the like button. Additionally, you can create a new partial to further customize the appearance:

# app/views/posts/liked_link.html.erb
<div id="like-button ">
 <p>"You liked this post!" </p>
</div>

In my modification, I changed the element from a link/button to a paragraph, but feel free to adjust it as needed.

I hope this clarifies things for you :)

Answer №2

Not quite sure if I grasp the query, but in case you aim to modify the like button:

To achieve this, you need to attach an event listener to the button. When it's clicked, a POST request should be sent to the appropriate route that deals with likes (along with the necessary parameters). Your controller should then respond by returning the like object (or data stored in the database). Upon successful post request, use the 'success' method to retrieve the like button and alter its appearance as desired.

$(“#like-btn”).click(function(){ 
Rails.ajax({
  url: "/some/url/to/like/controller",
  type: "post",
  data: [your post data],
  success: function(data) { $(`#${ data[“btn-name”] }`).attr(“color”, “blue”; }
})    
}

You can insert this script directly at the bottom of your HTML page.

You're not obligated to follow these exact steps, they are just meant to give you a general idea on how to structure the process using JavaScript and Ajax for handling post requests and updating the frontend, rather than relying solely on HTML buttons.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Getting a result from a Node.js function that includes a database query

Currently, I am diving into the world of Node.js and delving into working with MySQL connections. There is a particular function that should retrieve a set of rows from the database successfully. However, after retrieving these rows, I am unsure of how to ...

Sending database data from PHP to JavaScript - mysql_fetch_array behaving unexpectedly

Forgive me if there is already an answer out there to my question, but after a week of searching online and experimenting, I decided to turn to the experts for help. Purpose: My goal is to query an SQL database using server-side code (specifically PHP), t ...

retrieving data from a different controller in AngularJS

Having an issue with passing data from rootScope.reslogin2 to scope.user. It's not displaying as expected, here is my JavaScript file: app.controller("logincont", ['$scope','$http','md5','$window','$rootS ...

How should one correctly trigger an event in Google scripts?

When it comes to calling in the active elements, I have been using event.source.getActive and SpreadsheetApp.getActive. However, I have noticed that I sometimes interchange them in my script and face issues. So, I am unsure about which method is more app ...

Tips for Uploading Large Images to Backend API in Next.js

As I work on building my portfolio using NextJS, I encountered an issue with the Project Functionality. When converting images to base64 and sending them to an API for uploading on Cloudinary, everything runs smoothly as long as the total size of the req ...

Jest is having trouble recognizing a custom global function during testing, even though it functions properly outside of testing

In my Express app, I have a custom function called foo that is globally scoped. However, when running Jest test scripts, the function is being recognized as undefined, causing any tests that rely on it to fail. This is declared in index.d.ts: declare glob ...

When I click on my div, the color does not change as expected

Recently, I wrote a code snippet where there are 9 different div elements each assigned a ".spaces" class. The intention was to change the color of these divs upon clicking on them. However, I encountered an issue where only the first div changes its color ...

Transferring an array from PHP to jQuery through the use of AJAX

My JavaScript code communicates with a PHP page to retrieve data from a database and store it in an array. Now, I would like to use jQuery to loop through that array. This is how the array is structured: Array ( [0] => Array ( [image] => articl ...

Tips on looping through a universal array and retrieving user input

My current project involves creating a news site using the Guardian API. I want to implement a search feature that allows users to input keywords and retrieve the webTitle attribute for matching elements. While I could simply insert the user input directly ...

Calculate the total length of the nested arrays within an object

Check out this object: const obj = { name: "abc", arr: [{ key1: "value1", arr1: [1, 2, 3] }, { key1: "value2", arr1: [4, 5, 6] }] } I'm looking to find a way to quickly calculate the sum of lengths of arrays arr1 and arr2. ...

Explore the possibilities with Intel XDK's customizable keyboard feature

I recently started using Intel XDK for development and I encountered the following issue: I have an input text field (HTML) and I need to restrict user input to only numbers, decimals, and negative sign when they click on the field. How can I achieve this ...

HTML form submission with a grid of multiple choice options

I have created my own multiple choice grid: <div style="overflow-x:auto;"> <table class="w-100"> <tr> <td class="border"></td> <td class="border">Yes</td> <td class="border">No</ ...

What are the steps involved in generating and implementing dynamic hierarchical JSON data structures?

I am currently creating a dynamic diagram using d3.js that incorporates hierarchical data. The goal is to make it interactive so that users can manipulate the hierarchy by adding or removing data values and children. I'm wondering if there is a way to ...

{ 'Name:UniqueRewrite': { token: 738561, number: 2021.8 } }

Is there a way to extract the token value from this data in Node.js? console.log({'Name:Test': { token: 738561, number: 2021.8 } }) I need to isolate just the token and store it in another variable. ...

Requirements for adding information to a database table

I'm new to JavaScript and facing an issue that I need help with. I am trying to insert data into a database table based on certain conditions in my code, but even though I receive an error message when I input incorrect values, the data still gets ins ...

What are all the functionalities provided by jquery select?

Currently, I am venturing into testing out a new jQuery plugin. let myPlugin = new MyPlugin(); $(#myPlugin).someFunction(); console.log($(myPlugin)) I'm curious - is there a way for me to see a full list of the available functions/methods for me to ...

Recursive routing in NodeJS using Express

Certain website APIs have the capability to perform actions such as: Initial user's id their first friend, also a user v v GET /api/users/54282/friends/0/friends/0 ...

The addEventListener function seems to encounter issues in IE11

There is a javascript function below that uploads the selected file and updates the grid. It works perfectly in Firefox, but there seems to be an issue with IE11. The "ESignature/Registration" function within the addEventListener does not seem to execute ...

Is there a way for me to detect when the progress bar finishes and execute a different function afterwards?

After clicking a button in my Javascript function, the button disappears and a progress bar is revealed. How do I trigger another function after a certain amount of time has passed? $('#go').click(function() { console.log("moveProgressBar"); ...

The attempt to update several partial views using Jquery, MVC, and Json is currently malfunctioning

I am facing issues with updating multiple partial views using jQuery, MVC, and JSON. The partial views on my page are not getting updated. Below is the code for my view: Here is the code for my controller: public class GetStudentsController : Controlle ...