Is it possible that following or unfollowing a user through Ajax can result in the href attribute of other links changing? Check out the

Attempting to clarify a peculiar situation with as much detail as possible. Attached are images/examples.

A specific page is dedicated to displaying all the users a particular user follows.

users_controller.rb
def following
  @pals = current_user.following
end

following.html.erb
<% @pals.each do |pal| %>
  <div class="following-user-btn">
      <% if current_user_is_following(current_user.id, pal.wall.id) %>
          <%= link_to 'Following' , unfollow_wall_path(pal.wall.id), remote: true, method: :post, class: 'unfollow-button' %>
      <% else %>
          <%= link_to 'Follow' , follow_wall_path(pal.wall.id), remote: true, method: :post, class: 'btn follow-button' %>
      <% end %>
  </div>
<% end %>

Upon initial load, everything displays correctly, with the Following button next to each user and unfollowing functions properly. However, after clicking the unfollow button once, it changes the href for other users to the first one you unfollowed. You may not be able to Follow again if another user is currently utilizing the following button.


Here is my relationships controller and accompanying javascript:

def follow_wall
 if current_user.follow @wall.id
  respond_to do |format|
    format.html { redirect_to root_url }
    format.js { render 'walls/follow_wall' }
  end
 end
end

def unfollow_wall
 if current_user.unfollow @wall.id
  respond_to do |format|
    format.html { redirect_to root_url }
    format.js { render 'walls/unfollow_wall' }
  end
 end
end

Unfollow_wall.js.erb
$('.unfollow-button').bind('ajax:success', function(){
    $(this).closest('.unfollow-button').hide();
    $(this).closest('.following-user-btn').html('<%= link_to 'Follow' , follow_wall_path(@wall.id), remote: true, method: :post, class: 'btn follow-button' %>');
});


Follow_wall.js.erb
$('.follow-button').bind('ajax:success', function(){
    $(this).closest('.follow-button').hide();
    $(this).closest('.following-user-btn').html('<%= link_to 'Following' , unfollow_wall_path(@wall.id), remote: true, method: :post, class: 'unfollow-button' %>');
});

I attempted changing it to this:

$('#follow-button').attr('class', 'btn unfollow-button')
    .text('Following')
    .attr('href', "/<%= @wall.id %>/unfollow_wall")
    .attr('id', 'unfollow-button');

$('#unfollow-button').text('Follow')
    .attr('class', 'btn follow-button')
    .attr('href', "/<%= @wall.id %>/follow_wall")
    .attr('id', 'follow-button');

Unfortunately, no success with either method.

Note that the href is correct for all users upon refreshing the page. https://i.sstatic.net/molRS.png

When I unfollow the middle user, everything remains intact. https://i.sstatic.net/gZPFv.jpg

However, when I unfollow the top user, the top user's href changes to the middle user? This is where my confusion intensifies. https://i.sstatic.net/N6t5D.png

This issue has been puzzling me for days... Any assistance would be greatly appreciated. Thank you!

Answer №1

Consider refraining from attaching an ajax:success event in that specific part of the code.

Attaching an event with a function to an element implies that, moving forward, the element will be vigilant for the event and respond by executing the function whenever the event occurs. Therefore, it is essential to perform the attachment prior to the anticipated time of the initial event occurrence.

In Rails, the JS within unfollow_wall.js.erb will be executed as a reaction to clicking the button - this instance calls for triggering the function rather than binding it with an event.

My recommended approach is to avoid binding altogether and instead utilize the wall ID within the element identifiers on the page similar to this:

Take note of the ID of the outer div for each button here

<%# following.html.erb %>
<% @pals.each do |pal| %>
  <div id="following-user-btn-<%= pal.wall.id %>">
      <% if current_user_is_following(current_user.id, pal.wall.id) %>
          <%= link_to 'Following' , unfollow_wall_path(pal.wall.id), remote: true, method: :post, class: 'unfollow-button' %>
      <% else %>
          <%= link_to 'Follow' , follow_wall_path(pal.wall.id), remote: true, method: :post, class: 'btn follow-button' %>
      <% end %>
  </div>
<% end %>

Then in the JavaScript, simply locate the appropriate button using the correct ID within the outer div

# unfollow_wall.js.erb
$('#following-user-btn-<%= @wall.id %>').find('.unfollow-button').hide();
$('#following-user-btn-<%= @wall.id %>').html('<%= link_to 'Follow' , follow_wall_path(@wall.id), remote: true, method: :post, class: 'btn follow-button' %>');

The JavaScript code within the unfollow_wall.js.erb file mirrors what is presented here entirely, without being encapsulated in a bind function.

This same principle can be extended to the other JavaScript file as well.

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

Is it possible for me to ignore the outcome and treat a cross-domain AJAX response as JSONP?

When interacting with a network camera, I am sending a GET request to prompt the camera to move in specific ways such as pan, tilt, zoom, and more. I do not require any response from the camera's internal web server since it is hosted on a different d ...

Download button on Rshiny platform for collecting numerous files from different sources

I am on a quest for knowledge regarding the inclusion of a download button in my application that consolidates various files into a zip archive. Within my application, there are a timeline and a datatable, with files linked to entries on the datatable. Th ...

Methods to retrieve an array's value list dynamically using the 'id' in Vuejs

**User.vue** <template> <div> <div v-for="list in lists" :key="list.id">{{ list.val }} {{ list.kk }}</div> </div> </template> <script> import { datalist } from "./datalist"; export default { name: "User ...

New Relic identifies mysterious delays caused by MongoDB's findOne method

After setting up newrelic to pinpoint the bottlenecks in my app, I discovered a major issue that has left me stumped. The source of most delays seems to be mongoDB user.findOne, but the biggest challenge is locating where in the code this delay is occurri ...

Exciting discovery within my coding for US Number formatting!

I am currently working on formatting 10 digits to resemble a US telephone number format, such as (###) ###-####. Although my code successfully achieves this goal, it also has an unexpected issue that I'm struggling to identify. Specifically, when ente ...

Generate a list of keys along with an array containing sets of values

In my thesaurus app, users can enter a base word like "dog" and its synonyms like "canine, hound, mutt." Once entered, these words are stored in a database. However, to streamline the process and avoid multiple form submissions, I want to create simultaneo ...

The post page remains out of reach for Ajax

I've been struggling for hours to identify the issue with this code. I realized that I am unable to access the updateuser.php file even though it is in the same directory and the filenames are correct. Can someone please review the code below and let ...

Utilize JSON data as a source for autocomplete in JQuery

I have encountered an issue while using the autocomplete widget of JQuery with JSON to parse database information. Despite searching for a solution, I have not been able to resolve it. Here is my PHP file with JSON parsing: The error displayed in the brow ...

Utilizing jQuery AJAX in Internet Explorer 8

My current approach involves using a get request with $.ajax when the user submits a form. However, I'm unsure if my method (attaching a click event to the form button) is the most efficient or standard way to achieve this. If there is a more effecti ...

Ways to send a variable to a component through history.replace

Is there a way to retrieve the match.chatroomId in a functional component? I am currently using history.replace to navigate to this component. Here is the code snippet: onClick = {() => history.replace(`/chat/${match.chatroomId}`)} ...

Received an error while working on web development in Bootstrap with npm

I recently watched a freeCodeCamp video tutorial on web development which can be found here. Despite following the tutorial step by step, I encountered the following error message while running the webpack script: PS C:\Admin-Dashboard> npx webpac ...

javascript / php - modify input fields according to selection change

Can anyone help me with an issue I'm facing? I want to update multiple textfields whenever a new option is selected from my dropdown menu. I've written the following code, but it's not working as expected. Can someone figure out what's ...

React-file-viewer shrinks any document to a compact size

I have been searching extensively for information on how to adjust file sizing in react-file-viewer without any success. My objective is to utilize the react-file-viewer to allow users to click on a filename hyperlink and open the file (be it an image, do ...

Obtain the value stored in the session

How can I hide a form based on a specific session being set? Here is my approach: <form action="" method="post" <?php if ((isset($_SESSION['start']) )|| (isset($_SESSION['visitor']) )){ echo 'style="display:none;"'; } ? ...

What is the process for calculating the total sum of dropdown list values?

Here is the JavaScript function I am using: <script type="text/javascript"> $(document).ready(function() { $('#roomOptions select').change(function() { var total = 0; $('#roomOptions select').each(function() ...

Parsing JSON data with new line characters

What is the reason behind being unable to parse a json with a \n character in javascript? JSON.parse('{"x": "\n"}') Surprisingly, when you use JSON.parse(JSON.stringify({"x" : "\n"})), it works perfectly fine. indicates that {" ...

Passing a string array from View to Controller using Url.Action in MVC framework

I am facing an issue where I have a method that returns an array (string[]) and I am attempting to pass this array of strings into an Action. However, I am currently unable to pass my parameters as expected. Being new in MVC3, I would appreciate any insi ...

ng-repeat closing function event

Looking to create a callback method that gets called every time ng-repeat is triggered. After doing some research, I found a couple of options: 1. Using ng-init with ng-repeat This approach involves calling the method using the ng-init property: <ol ...

Tips for using Jquery to round up currency values

Is there a way to round up various currencies using jQuery? I have a specific requirement: 10.30 → 10 //Round down if below .5 10.60 → 11 //Round up if after .5 849.95 → 850 1,022.20 → 1022 ...

When trying to make a POST request, the browser displayed an error message stating "net::ERR_CONNECTION

Currently, my project involves coding with React.js on the client side and Express.js on the server side. I have encountered an issue when attempting to use the POST method to transmit data from the client to the server for storage in a JSON file. The erro ...