So basically I want to design my page in such a way that when a user leaves a comment, the page doesn't get refreshed, but the comment is sent and inserted into a database.
As such, I need to send the comment itself to the server, and I've read that the best way to do this is by using JavaScript FormData.The problem is that I can't get it to actually send something, and I want it to send to the server the data written in the type="input" element. I previously did this by using the default way provided by the HTML form element itself: action=link method="post".
So I wanna append the id of the campaign to the url and send the comment itself to the server by using $_POST and JavaScript DataForm if possible, so it knows the campaign that should have that comment.
I can have multiple campaigns and they're all gonna be generated 'dynamically' so to say, with PHP alongside JavaScript scripts to handle their behavior, so that's why I echo'ed all of that.
<form id="commentForm' . $row['id'] . '" name="commentForm" method="post" class="greyContainerAllCampaigns">
<input id="comment' . $row['id'] . '" name="CommentContent" max="250" title="max 250 alphanumeric and ,.?: etc chars" required pattern='.' \'[A-Za-z0-9 .,!?:\[\]()"-+]+\' ' .'class="inputBox" type="text" placeholder="write here">
<button id="commentB' . $row['id'] . '" class="submitButton" type="submit" name="Comment">Comment</button></form>';
That's the JavaScript script I tried to write in order to do that:
document.getElementById("commentB' . $row['id'] . '").addEventListener("click", commentFunction);
function commentFunction() {
fetch(\'http://localhost:80/proiect/GaSM/public/Campaign/comment/'. $row['id'] . '\', {
method: \'POST\',
body : new FormData(document.getElementById("commentForm' . $row['id'] . '")),
headers: {\'Content-Type\':\'multipart/form-data\'}
});
alert ("You left a comment!");
}
</script>';
I tried to get the result on the server with $_POST['CommentContent'] but I get nothing, nothing ever gets sent.
I'm obviously doing something wrong with the way I try to send it via POST to the server in the JavaScript script but I don't know what. Thanks in advance!