Search code examples
javascriptjqueryajaxdjangoposts

Can't use like button with ajax for each post in tape of posts


So, i got a like button for every post. But my ajax catch event only for new one post. Please explain me why ajax does not make it for every post in tape. And how to fix it.

Here is an ajax code.

{% block jquery %}
  $("#po-like").click(function(event){
      event.preventDefault();
      $.ajax({
          url: $("#po-like-href").attr('href'),
          success: function(){
          },
          error: function(response, error){
          }
       })
  });
{% endblock %}

Here is mine tape of posts.

{% for post in tape %}
    ...
    {{ post.text }}
    ...
    <a id="po-like-href" href="/like_post/{{ post.id }}/">
        <img id="po-like"  src="{% static "" %}"/>
    </a>
{% endfor %}

All others posts's like buttons work as if there is no ajax at all. If I click on them page reloads and number of likes changes


Solution

  • It's because of same id's in all a tags. You can have only one uniq #id in a html page. Instead you can change it to .class.

       {% block jquery %}
          $(".po-like").click(function(event){
              //changing #id to .class
              //added the below line
              var img = $(this);
              event.preventDefault();
              $.ajax({
                  url: img.parent().attr('href'),
                  success: function(){
                  },
                  error: function(response, error){
                  }
               })
          });
        {% endblock %}
    {% for post in tape %}
        ...
        {{ post.text }}
        ...
        //changing #id to .class
        <a class="po-like-href" href="/like_post/{{ post.id }}/">
            <img class="po-like"  src="{% static "" %}"/>
        </a>
    {% endfor %}