Improving voting functionality in Rails 4 with AJAX integration using the Thumbs_up gem

I've been struggling with creating a simple voting module using AJAX in Rails for the past four days. As someone new to Rails, I'm eager to learn what mistake I might be making!

The website's concept is straightforward - it features a list of posts (referred to as Topics) that users can vote on. I've implemented Devise for user models and Thumbs_up for handling votes.

Here's an excerpt from the view: index.html.erb

<td id='topic_<%=topic.id%>_votes'> <%= pluralize(topic.votes.count, "vote") %> </td>
<td><%= link_to('Vote for this post!', vote_up_topic_path(topic), :method => :post, :remote     => true) %></td>

Here's the controller snippet from topics_controller.rb

def vote_up
  current_user.vote_exclusively_for(@topic = Topic.find(params[:id]))
  respond_to do |format|
    format.js
  end
end

And here's the JavaScript code found in vote_up.js.erb under views/topics

<% if current_user.voted_on?(@topic = Topic.find(params[:id])) %>
  $('topic_<%<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b9c4d98897a0a1ab96bfa0bda2">[email protected]</a>%>_votes').html('<%= pluralize(@topic.votes.count, "vote") %>');
<% else %>
  alert("You can only vote on <%= @topic.title %> once!")
<% end %>

Despite the fact that the terminal shows that the vote_up.js.erb file is being processed when clicking on the vote link in the Rails server, there is no visible change in the browser. The number of votes only updates upon refreshing the page. While the vote is successfully recorded in the database, there's no immediate confirmation in the browser.

I would appreciate any insights on where I might be going wrong in this setup.

Answer №1

To ensure the Div is targeted using an ID, make sure to include a '#' before topic_<%[email protected]%>_votes in your vote_up.js.erb script.

Here's the correct format:

$('#topic_<%<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="477a073328372e24692e23">[email protected]</a>%>_votes').html('<%= pluralize(@topic.votes.count, "vote") %>');

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

Dividing internal CRUD/admin panel from the live application

Currently developing a moderately complex react app with redux. We have a production version that meets our requirements and now we are working on an administrative area for a local version of the application. This local version will only have basic CRUD f ...

Deciding between Bull queue and Database Triggers

My current project requires creating records in the database for users on a recurring basis, such as every Monday weekly or biweekly. I have identified two potential solutions to achieve this goal. One option is to utilize Database Triggers to generate ...

jQuery fails to display the response upon submitting JSON data

I'm encountering an issue with jQuery displaying a response after submitting data using JSON. Below is my HTML code: <input required="" width="100%" name="category_id" id="category_id" class="form-control"> <input required="" width="100%" ...

Using the parseInt method, you can easily combine integers and strings to perform addition and string concatenation simultaneously

Here is the code snippet I am working with: if (ev.data.type === "height") { if (ev.data.form === src) { setHeight(ev.data.message + "px"); } } Currently, the default height being added is 1900px. I would like to increase it by ...

Encountered the issue: "Received the error message 'MongooseServerSelectionError: Server selection timed out after 30000 ms.'"

I encountered the following error: MongooseServerSelectionError: Server selection timed out after 30000 ms while working with MongoDB Atlas. I attempted changing the useUnifiedTopology setting to false, which prevented my application from crashing. However ...

What is the functionality of an Angular service that retrieves an

It appears that Angularjs services are constructed by passing in a Contructor function: app.service('serviceName', function(){ this.var1 = 'foo'; this.method1 = function(){ } }); Angular executes this function using the new ...

Typescript - Promise resolves prematurely

I have been given a code with three essential parts that cannot be altered: 1. First, there is a call to the getData function, followed by printing the output. getData().then(console.log); 2. The function signature is as follows: async getData(): Promise ...

Issue encountered while managing login error messages: http://localhost:3000/auth/login net::ERR_ABORTED 405 (Method Not Allowed)

I am working on the /app/auth/login/route.ts file. import { createRouteHandlerClient } from '@supabase/auth-helpers-nextjs' import { cookies } from 'next/headers' import { NextResponse } from 'next/server' export async functi ...

What is the best way to utilize a JavaScript variable as a background within an inline style sheet?

I have a fun project for this evening - I am trying to make my website load a different background image every time the page is refreshed. Earlier on in this project, I managed to make the background interact with window size and screen resolution similar ...

The young ones whose height is 80% that of their taller parent's

Achieving the Desired Height In order to set a div with 80% of the height of its parent element without a defined height, I am aiming for a responsive effect. The Layered Layout Issue Within my layout consisting of five layers - .header, .site, .contain ...

encountering a loading issue with angular2-modal in rc1 version

Currently, I am implementing a library called angular2-modal. This library offers various modal options including bootstrap and vex for angular 2. While vex is functioning properly, I encounter an error when switching to bootstrap: responsive-applicati ...

Having Multiple Login Forms on a Single Page

I have encountered an issue with my login form code. It works perfectly as a single form, but I need to have 20 of these forms on one page. Despite my efforts to duplicate the code for each new form and adjusting the IDs, I am unable to make more than one ...

PHP-powered AJAX form validation

Currently, I am utilizing the PHP Zend framework along with jQuery ajax to validate and submit a form using json data format. Everything seems to be working smoothly - the PHP is functioning well and so is the ajax. However, I have encountered an issue whe ...

Enhance jQuery dialog form by populating it with specific record information

When I click the "Edit" button on a user records table, a jQuery dialog form appears to allow editing of the record. I've successfully stored the record values in jQuery variables and used them to populate the form. For text input elements, everythin ...

Experiencing difficulty retrieving the ID of a modal popup in JavaScript

I am facing an issue with my update panel and modal popup. The modal popup is located outside of the update panel, and when I try to access it from JavaScript using document.getElementById, $get or $find, it returns null as it cannot find the modal popup. ...

Guide to installing a dynamic favicon on a Next.js application for a specific route

I am trying to set up different favicons for my Next.js app based on the route. Here is where I want to implement this feature, displaying the country's flag as the favicon when a user navigates to that specific page. Below is the code snippet from m ...

Utilize jQuery to show a specific section of the page based on the hash in the URL

So, the inspiration for this project stemmed from a common issue I encountered: After hitting the register button, the PHP script processes it and displays an error, but the page remains on the login form. Here's the visual representation of the i ...

Javascript encountered an error upon attempting to return from the main function

I have a function that calls the database to perform an action: function callQuery(query) { db.query(query, (err, res) => { if (err) { // Error connecting to DB console.log(err.stack) } else { // Return the results ret ...

Stop Antd Modal from automatically scrolling to the top

At the moment, I'm utilizing Ant Design (v4.22.8) and Next.js (v12.3.4) in my project. One issue I've encountered is with a Modal component that activates when a button is clicked. Instead of overlaying the current content on the screen, the moda ...

Having trouble accessing the data I'm setting in a separate component using the Context API

Currently working on my own project and I've encountered a problem while using the Context API. It's my first time using it. The issue I'm facing is that I can't seem to console.log the data I'm setting. I'm trying to create ...