I'm trying to iterate over forms for likes with flask and AJAX. It works if there is just a single form and I use get element by id. What am I doing wrong in JS while iterating over the class?
HTML:
<form class="like_form" method="POST">
<input type="hidden" name="user_id" value="{{session['logged_in']['id']}}">
<input type="hidden" name="like_id" value="32">
<input type="submit" class="small_submit" value="๐ค">
</form>
<form class="like_form" method="POST">
<input type="hidden" name="user_id" value="{{session['logged_in']['id']}}">
<input type="hidden" name="like_id" value="32">
<input type="submit" class="small_submit" value="๐ค">
</form>
var like_form = document.getElementsByClassName('like_form');
for(var i = 0; i < like_form.length; i++){
like_form[i].onsubmit = function(e){
e.preventDefault();
console.log("clicked form")
var form = new FormData(like_form)
fetch("http://localhost:5000/test/form", { method :'POST', body : form})
.then( response => response.json() )
.then( data => {
console.log(data)
console.log(data['stars'])
const stars = document.getElementById("stars")
stars.innerHTML = `๐ ${data['stars']}`
})
}
}
You need to get the form data of one form, not the collection of forms. To make it work I would suggest using a for..of loop, with let to get block scope:
for (let lform of like_form) {
lform.onsubmit = function(e) {
e.preventDefault();
console.log("clicked form");
var form = new FormData(lform); // <---
A second issue is document.getElementById("stars"). That element does not exist in your HTML. Moreover, if this is supposed to be an element that relates to the form (one for each form), then note that id attributes should be unique in HTML, so you should select such elements differently.
Ended up having to iterate through with the index :( Worked really well to change the like on the page too!! Just used the index for both the submit and changing the number on the page. See like_count[i].value
let like_form = document.getElementsByClassName('like_form');
let like_count = document.getElementsByClassName('like_count');
for(let i = 0; i < like_form.length; i++){
like_form[i].onsubmit = function(e){
e.preventDefault();
console.log("clicked form")
var form = new FormData(like_form[i])
fetch("http://localhost:5000/test/form", { method :'POST', body : form})
.then( response => response.json() )
.then( data => {
if (data['stars']){
console.log(data)
console.log(data['stars'])
const stars = document.getElementById("stars")
stars.innerHTML = `๐ ${data['stars']}`
like_count[i].value = `๐ ${data['num']}`
}
})
}
}