D
D
DennyD3142017-01-10 16:27:58
JavaScript
DennyD314, 2017-01-10 16:27:58

How to like posts in news feed using django+ajax+jquery?

Hello!
There is a list of posts, I'm trying to make it possible to like the post I like (I just started to delve into the wonderful ajax technology). I can't bring it to mind. The display of likes in all posts is updated due to the fact that posts are displayed in a cycle and all have the same selector. When I make the id="likes_{{post.id}}" type selector, it turns out that the like is put down, but it is displayed only after the page is refreshed.
Please put me on the right path.
Template (piece) :

<button id="likes" data-catid="{{post.id}}" class="btn btn-primary" type="button">
        {% bootstrap_icon "heart-empty" %}  <span class="ajax_{{post.id}}">{{post.likes}}</span></button><br><br><br>


JQUERY:
$(document).ready(function (){
    $('.btn').click(function(){
        var catid;
        catid = $(this).attr("data-catid");
        var uniq_id = ".axaj_"+catid;
        $.get('/like_post/', {post_id: catid}, function(data){
            $(uniq_id).html(data);
        });
    });
});

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
DennyD314, 2017-01-11
@DennyD314

Djangobook forum members helped:
djbook.ru/forum/topic/5132/#post-32811
js :

function getAjax(divdett,pageload) {
    $(function(){$(divdett).load(pageload).show();});}

html :
{% for post in posts %}
    <button id="likes" data-catid="{{post.id}}" class="btn btn-primary" type="button"
            onclick="getAjax('.ajax_{{post.id}}','/like_post/?post_id={{ post.id }}');">
        {% bootstrap_icon "heart-empty" %}  <span class="ajax_{{post.id}}">{{post.likes}}</span></button><br><br><br>
{% endfor %}

But I'm completely at a loss, I don't understand what's wrong with what I wrote before... in debugging I put a bug on $(uniq_id).html(data); , I see the value uniq_id = ".ajax_3" for example, but the counter only increments after the page is reloaded. I change uniq_id to ".ajax_3" in the script - the counter is updated dynamically...

C
clojurerabbit, 2017-01-12
@clojurerabbit

Good afternoon.
It seems to me that you should not use a GET request to change the state. Yet semantically GET is idempotent. For all, even the simplest operations leading to a state change on the server, I would use at least POST (but here many will probably disagree with me).
As for the code, I don’t know if you made a typo in the code you ran or just when you moved it here, but you have a
typo in your line - it should still be .ajax, not .axaj

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question