Triggering AJAX call from several buttons within a single page in Django

Hey there! I'm currently working on implementing a voting feature using Ajax in my Django-based website. The issue I'm facing is that users can only vote on the first entry, but I want them to be able to vote on all entries. Can you assist me with modifying the code to achieve this?

Let's start with the HTML code, which simply displays a vote button for users:

{% for answer in answers %}<!-- django template -->
<strong id="vote_count">{{ answer.votes }}</strong> people have voted for this answer

{% if user.is_authenticated %}
        <button id="vote" data-answerid="{{answer.id}}" class="btn btn-primary" type="button">
        <span class="glyphicon glyphicon-thumbs-up"></span>
        Vote
        </button>
{% endif %}
{% endfor %}<!-- end django template -->

Next, here's the Django view responsible for processing the voting request:

@login_required
def vote_answer(request):
  answer_id = None
  if request.method == 'GET':
      answer_id = request.GET['answer_id']

  votes = 0 
  if answer_id:
      answer = Answer.objects.get(id=answer_id)
      if answer:
          votes = answer.votes + 1
          answer.votes = votes
          answer.save()

  return HttpResponse(votes)

Here's the URL mapping for this functionality:

url(r'^like_category/$', views.like_category, name='like_category'),

Lastly, check out the JavaScript code below:

$('#vote').click(function(){
    var answerid;
    answerid = $(this).attr("data-answerid");
    $.get('/vote_answer/', {answer_id: answerid}, function(data){
               $('#vote_count').html(data);
               $('#vote').hide();
    });
});

I hope that clarifies things! My main issue remains enabling users to vote on all entries on a single page instead of just the first one.

Answer №1

It is recommended to use the class attribute instead of id for <button> elements in order to allow multiple buttons to share the same jQuery event handler.

<button class="vote" data-answerid="...">

To implement this in JavaScript, you can use the following code:

$(document).on("click", ".vote", function(){
    var answerid;
    answerid = $(this).attr("data-answerid");
    $.get('/vote_answer/', {answer_id: answerid}, function(data){
               $('#vote_count').html(data);
               $('#vote').hide();
    });
});

This code will attach the event handler to any click on a <button class=vote>.

Additionally, it is advisable to use AJAX POST instead of GET for HTTP requests when performing a state-changing operation like voting. This helps prevent caching of results by browsers or web proxies, although jQuery does have its own cache buster mechanism.

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

What are the steps to creating a screen that mimics a mirror in the physical world?

Is there a way for the user to see themselves when they open a URL? I'm not looking for a mirror effect like the one produced by jQuery reflection js. I don't want to rely on using the front camera or any other camera to achieve this. Any sugges ...

Tips for transferring form data from controller to connection file

I'm currently working on creating a login page using Angularjs and node.js, but I'm encountering an issue with sending data from the controller to my database connection file for performing transactions. The error message reads: POST http://loca ...

Error: The function clickHandler has been referenced before it was declared or it has already been declared

Since I started using JSLint, I have encountered the common issues of "used before defined" and "is already defined." While I found solutions for some problems, I am currently stuck. Here is a snippet of my code: var foo; foo = addEventListener("click" ...

Parent-Child Communication in VueJS 2.0: How to effectively pass data from the parent component

Does anyone know a straightforward solution to this issue? I've been struggling to find one. Within my HTML file, there's a button that looks like this: <button @click="showModal">Show Modal</button> By clicking on the button, it t ...

The Ajax call resulted in a bad request error response

I keep receiving a bad request response when I make my request. I have confirmed that my dictionary data is correct by using an online JSON validator, and everything appears to be in order. Here is the code I am using: // Parse datetime to timestamp and a ...

Is there a method to access a website, trigger JavaScript functions, and subsequently retrieve the HTML content using PHP?

I am currently exploring options to access a webpage, execute JavaScript functions on it (thus altering the HTML content), and eventually save the modified version of the page. I'm uncertain if this approach is feasible, and if not, are there alternat ...

useEffect does not trigger a rerender on the primary parent component

I am facing an issue where the main parent component does not re-render when I change the state 'click button' in another component while using useEffect. Oddly enough, the main <App /> component only re-renders properly when I reload the p ...

Ways to obtain a referrer URL in Angular 4

Seeking a way to obtain the referrer URL in Angular 4. For instance, if my Angular website is example.com and it is visited from another PHP page like domaintwo.com/checkout.php, how can I detect the referring URL (domaintwo.com/checkout.php) on my Angul ...

I'm running into an issue with my React component where it is rendering before the state is set, causing it to fail. Is there a

Is it possible for me to achieve what I've been attempting for the past week? I feel like I'm so close, yet still can't quite reach my goal. Could it be that what I'm trying to do is impossible? I am using reactjs and next js (although ...

What could be the reason behind the index not getting properly set for the array that was cloned afterward?

I need assistance with a code snippet that clones an array, resets the index (0, 1, 2 ...), and stores it in a variable named buildingsPayload: console.log('1:', this.buildings) const buildingsPayload = this.buildings.map((building, index) => ...

Center the text within the div and have it expand outwards from the middle if there is an abundance of text

I have a div that is in the shape of a square box and I want it to be centered. No matter how much text is inside, I would like it to remain in the middle. I am using JQuery to create my square box and would like to center it using CSS. Here is my code: &l ...

Verify if an array contains a specific string while disregarding any additional letters within that string

Let's say I have a variable: var url = "/login/user"; Along with an array: var x = ["login", "resetpassword", "authenticate"]; My goal is to check if the url string exists within the array. The issue arises because the url contains additional char ...

Exploring the synergies of Remark and Rehype plugins alongside MDX in Next.js powered by @next/mdx

I’ve been experimenting with Github Flavored Markdown using @next/mdx, but I’m struggling to understand how to use plugins alongside the code. Here’s a breakdown of what I’ve attempted so far: (I’m following the instructions from the Next.js Doc ...

Updating input text value using jQuery - Chrome extension

I have been attempting to modify the input value on a specific website using a Chrome extension. To achieve this, I am utilizing jQuery in my content script. While it is effective in most scenarios, I encountered difficulty changing the input value when ...

While the data from Angular $resource can be viewed, it is not accessible in the code

As a newcomer to Angular, I'm facing a frustrating issue that I need help with. My $resource is fetching data from the server in key/value pairs like detail.name and detail.email. While I can access this data using {{detail.name}} in the view, I&apo ...

Just getting started with Django and running into some issues with model creation

Hi there! I seem to be encountering an unknown error while trying to create a model class (please see the code below). I've been following a tutorial on the official Django website, but unfortunately, it's not working as expected. I've spe ...

Issue: The module '[object Object]' could not be located

const express = require('express'); const app = express(); const jade = require('jade'); const path = require('path'); const server = require('http').createServer(app); const io = require('socket.io').liste ...

Encountering a problem with CRUD operations when attempting to edit and save data from a table using

When attempting to edit the information by clicking the radio button, the details are displayed in the appropriate boxes but the existing data in the table is deleted. My goal is to utilize a single array/scope variable for editing, displaying, and deletin ...

Looking for a node.js asset manager for converting coffeescript, jade, and stylus files to JS and CSS?

I specialize in using coffeescript, jade, and stylus for my projects. My task involves creating two separate "one page apps" where I need to include all assets within the initial payload. My goal is to consolidate, compile, and merge all coffeescript fil ...

Display a single item using Jquery when clicking on an element with the same class

I'm relatively new to JQuery/Javascript scripting and I'm having some difficulty. How can I display one item with the same class without affecting the other items? Here is my code: $(function() { $('.embedContainer > .myPosterImage& ...