AJAX call not working on EJS multiple forms (works just on the first form)

Viewed 24

I have a like button on multiple posts, in EJS. Problem is, when I am clicking the first like button, the form sends and updates the View accordingly.

When I click the other buttons they all seem to send and update the first form, and they also update the first button adding the 'active' class to it.

I tried deleting the IDs and adding classes, still same result.

My guess is there is a fault in my AJAX or HTML structure because form is updating the database with no problem.

HTML:

<form id='like' action="/postLike/<%=blogposts[i]._id%>?_method=PATCH" method="POST">
            <% if (blogposts[i].liked == false) {%> 
            <div id='likeBtn' onclick="Like()" class="wrapperHearts">
            <svg xmlns="http://www.w3.org/2000/svg" id="Love"><path d="M28.124,15.5615,16.7549,28.6558a1,1,0,0,1-1.51,0L3.876,15.5615A7.6866,7.6866,0,0,1,2.57,7.61a7.1712,7.1712,0,0,1,6.085-4.5752C8.915,3.0122,9.1768,3,9.4424,3A8.6981,8.6981,0,0,1,16,6.0083,8.6981,8.6981,0,0,1,22.5576,3c.2656,0,.5274.0122.7862.0352A7.1713,7.1713,0,0,1,29.43,7.61,7.6866,7.6866,0,0,1,28.124,15.5615Z" style="fill:#212123"/></svg>
            </div><%}%>
            <% if (blogposts[i].liked == true) {%> 
                <div id='likeBtn' onclick="Like()" class="wrapperHearts active">
                <svg xmlns="http://www.w3.org/2000/svg" id="Love"><path d="M28.124,15.5615,16.7549,28.6558a1,1,0,0,1-1.51,0L3.876,15.5615A7.6866,7.6866,0,0,1,2.57,7.61a7.1712,7.1712,0,0,1,6.085-4.5752C8.915,3.0122,9.1768,3,9.4424,3A8.6981,8.6981,0,0,1,16,6.0083,8.6981,8.6981,0,0,1,22.5576,3c.2656,0,.5274.0122.7862.0352A7.1713,7.1713,0,0,1,29.43,7.61,7.6866,7.6866,0,0,1,28.124,15.5615Z" style="fill:#212123"/></svg>
                </div><%}%>
            </form>

AJAX:

    let likeButton = document.querySelector('.wrapperHearts');
let frm = $('#like');

function Like(){ frm.submit()}

frm.submit(function (e) {
  e.preventDefault(e);

  var formData = new FormData(this);


  $.ajax({
    async: true,
    type: frm.attr('method'),
    url: frm.attr('action'),
    data: formData,
 
    processData: false,
    contentType: false,

    success: function (data) {
    console.log("success");
    
    console.log(data)
    if (data.liked == false){
    likeButton.classList.add('active')
    $("#likesNumber").text(data.likes +1 + ' ' + 'Likes')
      
    }
    else{
    likeButton.classList.remove('active')
    $("#likesNumber").text(data.likes -1 + ' ' + 'Likes')   
    }
},
    error: function(request, status, error) {
      console.log("error")
    }
    
  });

});

In the form I am using method-override.

0 Answers
Related