Ruby on Rails and JSON: Increment a counter with a button press

How can I update a count on my view without refreshing the page when a button is clicked?

application.js

$(document).on('ajax:success', '.follow-btn-show', function(e){
  let data = e.detail[0];
  let $el = $(this);
  let method = this.dataset.method;
  if (method === 'post') {
    $el.text('Unfollow');
    this.dataset.method = 'delete';
  } else if (method === 'delete') {
    $el.text('Follow');
    this.dataset.method = 'post';
  }
});

The code above changes the button text perfectly. But now how do I update a count in a different div upon click? I attempted:

$(this).text(${data.count});

However, it updates in the wrong place. How can I assign the correct attribute to my script for the update?

Here's the count in my view

<div class="loop"><b><%= @user.followers.count %></b></div> Followers

Controller

def create
    current_user.follow(@user)
    respond_to do |format|
      format.html
      format.json do
        render json: { count: @user.followers.count },
               status: :created  
      end
    end
  end

  def destroy
    current_user.unfollow(@user)
    respond_to do |format|
      format.html
      format.json do
        render json: { count: @user.followers.count }, 
               status: :ok
      end
    end
  end

Any suggestions or guidance would be appreciated!

Thanks

Answer №1

My solution involves reloading the div with the specified id after a click event...

$(document).on('ajax:success', '.follow-btn', function(e) {
  let data = e.detail[0];
  let method = this.dataset.method === 'post' ? 'delete' : 'post';
  let txt = {
    post: 'Follow',
    delete: 'Unfollow'
  }[method];
  //loop through each follow button
  $(`.follow-btn[href="${this.getAttribute('href')}"]`).each(function() {
    this.dataset.method = method;
    $(this).text(`${txt}`);
  });
   $("#following_count").load(" #following_count > *")
});

Within my perspective

<div id="following_count" class="inline"gt;...<%= current_user.following.count %>...</div>

Although not perfect, this method proves to be effective and functional.

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

Ways to retrieve a specific value in an array of objects

When working with the p5 javascript library, there is a convenient built-in function called {key} that captures the key you press. For instance, using text(${key},200,200) will display the key pressed at position 200, 200 on the canvas. If I were to stor ...

Obtaining the calculated background style on Firefox

Back when my userscript was only functional on Chrome, I had a setup where I could copy the entire background (which could be anything from an image to a color) from one element to another. This is how it looked: $(target).css('background', $(so ...

Avoiding Vue Select from automatically highlighting the initial option: tips and tricks

Currently utilizing Vue Select as a typeahead feature that communicates with the server via AJAX. By default, the first option from the server response is highlighted like this: https://i.stack.imgur.com/jL6s0.png However, I prefer it to function simila ...

How does the functionality of $.ajax differ from that of $.get?

Similar Inquiry: Understanding the Variations of $.ajax(), $.get(), and $.load() I'm curious about the disparities between $.get() and $.ajax The given code showcases calls like this: $.get(href) .success(function (content) { $(&apos ...

Utilizing Typhoeus::Request in Ruby on Rails to dispatch a request to FCM (Firebase Cloud Messaging

I've been struggling for hours trying to figure out why my simple request to FCM using Typhoeus::Request is not working. Despite my efforts, I can't seem to find the issue... This is the code I'm using to send the request to FCM: req = Typ ...

How can you stop a document event listener from triggering?

Utilizing document.addEventListener('touchstart', this.onDocument); allows me to recognize when a user taps outside of an element. However, within my button click handler, the following code is present: toggleItemActive(e) { e.stopPropa ...

Error Encountered with Next.js 13.4.1 when using styled-components Button in React Server-Side Rendering

I am currently working on a React project using Next.js version 13.4.1 and styled-components. One problem I'm facing is with a custom Button component that I've created: import React from 'react'; import styled from 'styled-compone ...

Selenium Python Slider Button Element Visibility Issue

Currently, I am developing a parser to automate the process of clicking buttons on a website. However, I am encountering difficulties in clicking two specific buttons. The buttons I am aiming to click are "Elija el imports a financiar" and "Elija la mensu ...

Managing toggles for save and edit buttons in Vue - a comprehensive guide

I am currently working on a Vue 'app' within a larger Django application as a means to enhance my understanding of Vue. My objective is to create unique forms that can be edited independently. I have been experimenting with this for some time n ...

Prevent parent element from triggering double click when double clicking on children element with CSS or jQuery

Check out my project demo here Whenever I double click on a child element, it also triggers the parent element at the same time. I want to prevent this behavior so that only the child element is affected by the double click event. Can anyone provide assis ...

What is the best way to verify if an Android permission request has been successfully granted or denied

I've been working on my RN application and encountered the following code snippet. import { PermissionsAndroid } from 'react-native'; export default new Promise(() => { return PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS ...

How to successfully transfer input data from a dialog to a controller using jQuery and Grails

As a newcomer to Grails and jQuery, I recently created a jQuery dialog following this example: http://jqueryui.com/dialog/#modal-form The goal is to open a dialog, input data, and have it displayed in a dynamic table on the main page. Once all entries are ...

Retrieve element attributes and context inside a function invoked by an Angular directive

When working with a directive definition, you have access to the $element and $attrs APIs. These allow you to refer back to the element that called the directive. However, I'm curious how to access $element and $attrs when using a standard directive l ...

Optimal approach for vertically aligning elements in CSS

I'm looking to arrange my header ('Sail away today with Starboard Rentals.') and link buttons on top of each other. I want the navigation buttons to be positioned below the h1 on the lower half of the 'home-jumbo' div. What's ...

Conceal an item if the span element encompasses a div with a specific class

I am struggling with a problem where I need to hide an "i" element only if a "span" contains a "div" element. The content inside the "span" is loaded via AJAX and rendered as HTML, so it may contain the "div class=difference" or not. The code snippet in q ...

Encountering an 'undefined' property error when clicking a button in Angular 1.x

Hey there, I have a question that might seem simple to some of you. I'm struggling with fixing an error and I don't quite understand why it's happening :( This error popped up while using Angular 1.x. What I need help with is creating an al ...

Creating a new function within the moment.js namespace in Typescript

I am attempting to enhance the functionality of the moment.js library by adding a new function that requires a moment() call within its body. Unfortunately, I am struggling to achieve this. Using the latest version of Typescript and moment.js, I have sear ...

Looking to change the date format from 24/05/2021 to 24/May/2021 using jQuery or JavaScript?

My client prefers not to use a date picker, but wants to be able to type dates directly into a textbox and have them automatically converted to the format 24/May/2021 as they leave the field. I am looking for a solution using either Javascript or jQuery. ...

Is it possible to utilize hooks such as 'useState' within an async/await server component?

'use client' async function Teachers (){ const response = await fetch('http://localhost:8000/teachers', }) const data = await response.json(); const [showNames , setShowNames] = useState(false); // Unable t ...

Issue in IE with click event not firing from parent page

Currently, I am facing an issue with a filter on one of my website's pages that is designed to display various products. My goal is to set it up so that when a button from an external page is clicked, the user will be redirected to the product page wh ...