Creating a like button using AJAX in Django

Is there a way to implement a like button in Django using ajax without the need for a page reload? I've tried setting up my HTML and Ajax function, but it's not working properly.

  <form method="POST" action="{% url 'video:like' video.pk %}">
  {% csrf_token %}
  <input type="hidden" class="likin" name="next" value="{{ request.path }}">
  <button class="remove-default-btn" type="submit">
      <i class="fa fa-thumbs-up" aria-hidden="true"><span>{{ video.likes.all.count }}</span></i>
  </button>

JavaScript

    $('.likin').click(function(){
$.ajax({
         type: "POST",
         url: "{% url 'video:like' video.pk %}",
         data: {'content_id': $(this).attr('name'),'operation':'like_submit','csrfmiddlewaretoken': '{{ csrf_token }}'},
         dataType: "json",
         success: function(response) {
          selector = document.getElementsByName(response.next);
                if(response.liked==true){
                  $(selector).css("color","blue");
                }
                else if(response.liked==false){
                  $(selector).css("color","black");
                }


          }

    });

})

Answer №1

Instead of attaching an event to the button click, consider adding an event to the form submission to prevent it. Then, you can submit the form using AJAX for better control.

To begin, give your form tag an id:

<form method="POST" action="{% url 'video:like' video.pk %}" id="my-like-form">

Next, add an event listener for the form submission:

$("#my-like-form").submit(function(e){
    e.preventDefault(); // Stop form submission
    let form = $(this);
    let url = form.attr("action");
    $.ajax({
        type: "POST",
        url: url,
        data: form.serialize(),
        dataType: "json",
        success: function(response) {
            selector = document.getElementsByName(response.next);
            if(response.liked==true){
                $(selector).css("color","blue");
            } else if(response.liked==false){
                $(selector).css("color","black");
            }
        }
    })
})

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

Utilizing Angular to augment existing items in local storage

Hey everyone, I'm facing an issue with localStorage that I can't seem to figure out. I have a form where the first step collects name and gender, and the second step asks for weight and height. The data from step 1 is saved in localStorage, but ...

Is it necessary to include compiled JavaScript files in the Git repository?

Just starting out with TypeScript and curious about best practices according to the community. For production compilation, I currently use the webpack loader. However, during testing, I find myself needing to run tsc && ava. This results in the cr ...

utilizing the .each method to retrieve values from JSON data

When sending data from my PHP server-side code to the client side using Ajax, here is how it's done: //server side $json='{ "payout_history":"0", "round_shares":"1816", "workers": { "jbo.5970": { "alive":"1", "hashrat ...

Automated Recommendation Selector

I'm searching for a JavaScript library that can provide the following functionalities: An auto-suggest dropdown list that uses Ajax to retrieve results from a database. Restricting the user to only select values provided by the Ajax call. Abilit ...

My JavaScript code is functioning properly in jsfiddle, but when I try to run it on my own website, I encounter

Encountered an error message stating "Uncaught typeError: cannot call method 'hover' of null" following the line $('#nav li a').hover(function(){ in my JavaScript code. Check out the code on my site here: http://pastebin.com/GjZBEu3s Y ...

Unable to display individual elements of an array using the map function in React Native

Below is my react-native code that I am using to display a list of array elements using the map function. import React from 'react'; import { createStackNavigator } from '@react-navigation/stack'; import {Card} from 'react-native-e ...

Send the checkbox value using ajax, jquery, and php

Hey everyone, I'm facing an issue and need some help. I am trying to send the value of a checkbox via AJAX to a PHP file. My question: I want to pass the checkbox value regardless of whether it is checked or not. If it is checked, then the value "tr ...

Is it more effective to utilize Selenium or simulate an XHR request when using Python Scrapy?

I am looking to extract data from a large online marketplace website that utilizes ajax pages. My plan is to deploy this on a Centos VPS so I can regularly gather data and improve my product offerings. While I am inexperienced with Python, Scrapy, and web ...

Passing values between PHP and jQuery using Ajax to compare with a variable is a common task in web development

I'm struggling to get my PHP and jQuery script to work properly. The goal is to pass a value through Ajax, have PHP check it to see if it matches and increment the score by 1. Here is the code I've written: <?php $score = "1"; $userAnswer = ...

I am wondering why the vue-router is only changing the URL and not displaying the corresponding view component

I've encountered an issue where the vue-router is only toggling the URL when clicking on the navigation link, but not updating the view component. Surprisingly, there are no apparent errors in my code. Despite this, the console indicates that the Home ...

Just starting out with Python Django, seeking advice on automatically filling in a field

Is it possible to automatically populate the 'amount' field in my model.py based on the user's selection from a multi-choice drop-down menu? For example, if the user selects "Gas" from the menu for type, can the amount field be auto-populate ...

Prevent the instant spread in the AJAX success function

Here is a snippet of my code: $(document).on('click', '[data-submit-form]', function (event) { var form = $(this).closest('form'); $.ajax({ url : form.attr('action'), type : 'post' ...

Transitioning effect when tapping a link that guides you to a different section of the webpage

Just by reading the title, you can understand my concern. Currently, when I click on "Example 4", the page abruptly scrolls to the h1 of Example 4. It looks so ungraceful, like a sudden boom. I would prefer a smooth scrolling effect. Is it possible to achi ...

What is the best way to extract the event time when a user clicks on an event in fullcalendar?

Is there a way to extract only the time from an eventclick event in fullcalendar? Currently, I am receiving details about the event including date and time. How can I specifically retrieve just the time (e.g. 6:00:00 am)? You can find the code snippet tha ...

Generating a hierarchical structure of JSON data through iterative looping

Currently, I am in the process of creating a directive within Angular to assist with field validation. The functionality is working smoothly until it comes time to store the validation result. My objective is to store this information in an object structu ...

JavaScript: Developing an interactive Word Guessing Game

Here's some sample code: let ccdisplay = document.querySelector('.crrDisplay'); let incdisplay = document.querySelector('.incDisplay'); let guess = document.querySelector('#character'); let textForm = document.q ...

Utilizing MongoDB Data in an .ejs Template Using Node.js Express

After going through numerous tutorials, I find myself stuck at a point where I am struggling to render all the data written by my express-app into MongoDB in embedded JavaScript. My goal is to display this data in a simple table that always shows the updat ...

Adjust the size of an IFRAME to eliminate scrollbars from appearing

My webpage features an iframe that needs to be resized dynamically each time its contents change in order to eliminate scrollbars. The content inside the iframe frequently changes without altering the URL. I desire for all the content within the frame to b ...

How to Fix: jQuery UI Autocomplete Suggestions Remaining Open After Selection

I'm experiencing an unusual issue with a jQuery UI autocomplete feature. I have it set up so that when the text field is focused, a list of all options in the autocomplete appears. While this works as intended, selecting an item by clicking on it caus ...

Can you identify the issue within this code that combines HTML5, CSS, and JavaScript?

I'm attempting to create a feature where, upon clicking a button, a hidden div will be revealed. However, my current implementation doesn't seem to be working. function reload(){ window.reload(); } function vis(x,z,a){ var xpar = docu ...