Answer the question
In order to leave comments, you need to log in
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>
$(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
Djangobook forum members helped:
djbook.ru/forum/topic/5132/#post-32811
js :
function getAjax(divdett,pageload) {
$(function(){$(divdett).load(pageload).show();});}
{% 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 %}
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 questionAsk a Question
731 491 924 answers to any question