Answer the question
In order to leave comments, you need to log in
How to write ajax requests correctly?
Good afternoon! I ask you not to throw slippers, I'm still completely green in js, but the task is worth it and I need help.
I have, let's say, several articles, and I need to write the article evaluation functionality.
I will describe the code like:
<div>
<p>статья1</p>
<a class='like_button' onclick="createajax()" href="#" data-id="{{ article.id }}" data-action="like'>
<span class='total-likes'>0</span>
</div>
<div>
<p>статья2</p>
<a class='like_button' onclick="createajax()" href="#" data-id="{{ article.id }}" data-action="like'>
#всего лайков
<span class='total-likes'>0</span>
</div>
$(document).ready(function(){
{% block domready %}
function createajax(e){
e.preventDefault();
$.post('{% url "review-like" %}',
{
action: $(this).data('action'),
id: $(this).data('id'),
},
function(data){
if (data['status'] == 'ok')
{
var previous_action = $('a.like_button').data('action');
// toggle data-action
$('a.like_button').data('action', previous_action == 'like' ?
'unlike' : 'like');
// update total likes
var previous_likes = parseInt($(total-likes).text());
$(total-likes).text(previous_action == 'like' ?
previous_likes + 1 : previous_likes - 1);
}
}
);
};
Answer the question
In order to leave comments, you need to log in
Add a submit button and hang an event on it:
$('#selector').on('click', function() {
/* your code here */
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question