maheshkumar maheshkumar - 2 months ago 5
Ajax Question

AJAX call is triggered only in the first link and not in any other links inside a for loop

I have an issue in implementing AJAX call for all the links inside for loop in Python Flask application.

Only the first link triggers AJAX call and no other links triggers AJAX call.

Below is the code of the respective .html and .js file I have implemented.

.html

{% for article in articles %}
{% if article._id in likes %}
<button data-toggle="tooltip" title="Unlike" id="unlike-button" value="{{article._id}}"><span id="user-like-recommend" class="glyphicon glyphicon-heart" aria-hidden="true"></span></button>
{% else %}
<button data-toggle="tooltip" title="Like" id="like-button" value="{{article._id}}"><span id="user-like-recommend" class="glyphicon glyphicon-heart-empty" aria-hidden="true"></span></button>
{% endif %}
{% endfor %}


.js

document.getElementById("like-button").addEventListener("click", function(e) {
e.preventDefault();
var article = $('#like-button').val();
var data = {"article": article};
console.log(data);
if(data){
$.ajax({
type: 'POST',
contentType: 'application/json',
url: '/article_liked',
dataType : 'json',
data : JSON.stringify(data),
success: function (response) {
success("Article was successfully liked.");
}


What should I do to fix this issue?

Answer

Change the ids into classes, ids must be unique

{% for article in articles %}
  {% if article._id in likes %}
    <button data-toggle="tooltip" title="Unlike" class="unlike-button" value="{{article._id}}"><span id="user-like-recommend" class="glyphicon glyphicon-heart" aria-hidden="true"></span></button>
  {% else %}
    <button data-toggle="tooltip" title="Like" class="like-button" value="{{article._id}}"><span id="user-like-recommend" class="glyphicon glyphicon-heart-empty" aria-hidden="true"></span></button>
  {% endif %}
{% endfor %}

js:

$(".like-button").on("click", function(e)    {
e.preventDefault();
var article = $(this).val();
var data = {"article": article};
console.log(data);
if(data){
  $.ajax({
    type: 'POST',
    contentType: 'application/json',
    url: '/article_liked',
    dataType : 'json',
    data : JSON.stringify(data),
    success: function (response) {
      success("Article was successfully liked.");
    }
Comments