The like count displayed in Django's AJAX feature is identical for every post

Having an issue with the ajax setup in my django twitter clone app. Every post's like count remains the same after clicking the like button, but it gets updated after a page refresh. I'm close to fixing it, but currently stuck.

View:

def add_like(request):
    if request.method == 'GET':
        ans_id = request.GET['id']
        user = request.user.profile
        liked_tweet = get_object_or_404(Tweet, pk=ans_id)

if ans_id:
    # creating instance by sending the Like table fields
    instance, created = Like.objects.get_or_create(liker=user, liked_tweet=liked_tweet)
    ans = Tweet.objects.get(id=(int(ans_id)))
    if ans:
        likes = ans.likes + 1
        ans.likes = likes
        ans.save()
# returns the likes field of a tweet post
return HttpResponse(likes)

The issue seems to be caused by the HttpResponse returning the likes value.

Template:

    {% for tw in tweets %}
    <div class="blog-post">
        <p>
            {{ tw.content|safe }}<br><hr>
            <small class="small">
                লিখসে -
                <a href="{% url 'profile' pk=tw.tweeter.user.pk %}">{{ tw.tweeter.user.username|capfirst }}</a>
            </small>
        </p>
        {% if user.is_authenticated %}
        <button class="btn btn-default likes-button" type="button"
        data-ansid="{{ tw.pk }}">Like</button>
        <i> Total Likes: </i><em class="like_count">{{ tw.likes }}</em>
        {% endif %}
    </div>

Ajax script:

$(".likes-button").click(function(e) {
if ($(this).html() == "Like") {
    $(this).html('Unlike');
    //alert("js working");
    // error was there for "data" insted of "attr"
    var ansid = $(this).attr("data-ansid");
    $.ajax({
        url: '{% url "add_like" %}',
        type: 'get',
        data: {id: ansid}
    }).done(function (data) {
        alert("success");
        $('.like_count').html(data);
        //$('#likes').hide();
    }).fail(function (err) {
        alert(err);
    });
}

Appreciate any assistance.

https://i.sstatic.net/weywB.png https://i.sstatic.net/psHdR.png

Answer №1

The initial input given by Sayse seems to address your question, and I'm here to offer further clarification.

Essentially, what you have done is replace the existing like count with data received from an ajax request in any element that has a class called .like_count.

Take a look at your code: $('.like_count').html(data); This line selects all elements with the class like_count and updates the HTML content.

Instead, after a successful ajax request, consider updating the data in just one specific location. You need to choose the appropriate jquery selector.

You could use something like .closest(). For instance, (the following code is untested)

$(this).closest('.like_count').html(data);
to insert the 'like count' in the right element.

Alternatively, you can assign dynamic IDs to each 'like count' element based on their ID and then utilize the exact ID Selector.

I hope this information proves helpful to you.

Cheers!

Answer №2

Were you mentioning this:

However, once the page is refreshed it should be fine

If your code snippet is functioning correctly, all you need is for the likes count to increment and display the live update in the template.

Basically, what needs to happen is:

  • The function responsible for incrementing the likes should return a JSON response with the updated value from the database.
  • A client-side function can then receive this JSON response and update the template accordingly.

In practice:

  • You can refer to this answer:

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 is the ideal event to trigger a response when the user completes entering text into the search field in Vue.js?

I am currently utilizing a text field from the Vuetify library to filter a table within my application. <v-text-field style="min-width: 300px;" v-model="filterString" label="Search" /> The functionality is straigh ...

Obtain JavaScript object from WebView in Swift

Currently, I am displaying a webView in my iOS app using Swift. My goal is to retrieve an object from the JavaScript code within the webView. Upon inspecting the console, I discovered that the desired object is named "window.user". However, when attempti ...

Is there a way to arrange an array based on the product or quotient of two values?

I'm working with an array of posts, each containing data on 'views' and 'likes', along with the user IDs associated with those likes. My goal is to sort this array based on the like rate. However, my current approach seems to be i ...

css failing to load properly following javascript redirection

Upon clicking the button labeled id=cancel, the user will be directed to index.php. $('#cancel').click(function() { if(changes > 0){ $('#dialog-confirm').dialog('open'); }else{ window.location.href = ". ...

Tips for changing a entry with Ajax on WordPress

I apologize if this question has already been addressed. I am new to Ajax and currently attempting to modify a record within the users table of WordPress. Utilizing a for loop to display users, the query is as follows: foreach($user_info as $newu){ ?> ...

Guide to setting up an automated process in PHP

When setting up a tournament interface on my page: Users utilize functions like fopen() and fwrite() to create tournaments. The created tournaments must only start after a specific time, for example, 1 hour. This delay allows other users to join the tour ...

Using a single AJAX function to write on various tags

Information regarding the likes and dislikes count is retrieved from the server using an ajax function with the following queries: $q3="select count(value) as a from rank where personID='$person' and itemID='$itemID' and value>0 ...

Encountering a 405 error when attempting to send a request through an express route in a Next

After deploying my Express js routes in Next js on hosting, I encountered an error 405 when sending requests to the route. However, everything works fine when I test it on localhost. I'm puzzled by this issue. Can anyone help me understand what' ...

The function chartobject-1.render() is returning an error message stating: "Unable to locate the specified container within the document. This issue is occurring in the

I've encountered an issue while trying to integrate FusionCharts into my Vue.js project. Every time I attempt to render the charts within my components, I consistently run into this error. Here's a snippet of one of the components: <template&g ...

transmitting comfort through events

To enhance my application, I am working on publishing a solace message to a topic and then passing it along to another part of the app for further processing using events. This entire process is happening within a single node.js process. While I understand ...

Tips for utilizing Vue 'component' with just Vue added as a page add-on using <script>:

I am trying to incorporate a Vue component called vue-timeago: import VueTimeago from 'vue-timeago' Vue.use(VueTimeago, { name: 'Timeago', // Component name, `Timeago` by default locale: undefined, // Default locale locales: { ...

Exploring the combination of Babel and Next.js: Integrating custom scripts into a project

Hello, I am currently learning next.js and facing a common issue that I need help with. I have created my own ES6 JavaScript library and now I want to convert it to babel so I can use it in my next.js application. Is there a way to configure babel for sp ...

Exploring Parameters to Customize Search Results in React

I am currently working on implementing a data filtering system based on user input. However, it seems that the data disappears whenever I enter something into the search box. Upon inspecting the dev tools, I can see that the query state is being saved pro ...

Creating a JSON representation of a single entry in a Django model object

I am working with a model Y that has 3 fields, and there are currently 5 entries in this model. While I am aware of the method to serialize all entries in JSON format using Django's serializers module: from django.core import serializers def aMetho ...

Vue.js: Attaching a function to a Template

I am struggling to find a way to bind my screen height to a calculated value in my code. Unfortunately, the current implementation is not working as expected. I would greatly appreciate any guidance on how to resolve this issue. <template> <b ...

Issue with offset calculation in bootstrap table occurs when the bootstrap-table is closed and the window is resized

In a recent project, I utilized the bootstrap table. However, upon closing the bootstrap table with the following script: $(document).ready(function () { $(".removetable").click(function (e) { $(".table-aria").remove(); ...

Crafting a robust and secure password using Yup and Formik while receiving personalized error notifications

My Password Validation Dilemma I'm in the process of developing a password field that can assess the strength of the input provided. In a different response, I came across a regex that I could utilize to validate whether the input meets specific crit ...

Using arrays as data in an Ajax request for DataTables

Struggling to send selected row IDs to an API using the DataTables Ajax option. Despite numerous attempts, I can't seem to get the IDs sent as an array. Below is a sample code I've tried. It generates the URL: getStatistics.php?ids=1&ids=2& ...

What causes Angular2 to detect both reference changes and primitive changes even when the OnPush flag is enabled?

Take a look at this code snippet import {Component, OnInit, Input, OnChanges, DoCheck, ChangeDetectionStrategy} from 'angular2/core' @Component({ selector: 'child1', template: ` <div>reference change for entire object: { ...

Attaching a click event to a nested element within an AngularJS directive

I am currently working with the following directive. (function () { 'use strict'; angular.module('ap.App') .directive('clearCancelFinishButtonsHtml', function () { return { scope: { ...