B
B
bituke2021-09-17 11:45:43
AJAX
bituke, 2021-09-17 11:45:43

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>

This is the html code, js:
$(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);
        }
      }
    );
  };

I really need help) As I understand it, we need a function that will send ajax when clicked. How can this be universally spelled out?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
Gennady, 2021-09-17
@gkukuruz

Add a submit button and hang an event on it:

$('#selector').on('click',  function() {
     /* your code here */
});

Inside the function, write the rest of the logic

D
Developer, 2021-09-17
@samodum

which will send ajax on click

A request is sent. AJAX is a technology

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question