2

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!

2 Answers 2

1

how about you give the form a class and in javascript add an event to this form whenever it is submitted to make an Ajax request to the form action with the data of thr e form serialized.

$(“.form”).on(“submit”, function(e) {
    $form = $(this);
    $.ajax({
        url: $form.attr(“action”),
        type: “post”,
        data: $form.serialize(),
        success: function(res) {
            alert(“success”);
        },
        error: function(error) {
            alert(“error”);
        }
    });
    e.preventDefault();
    return false;
});
Sign up to request clarification or add additional context in comments.

2 Comments

Easiest way is to put hidden inputs in each form indicates to what campaign by id maybe
The comment will be sent automatically as long as it is a valid form element inside your form
1

First, give your form element a normal id. Not sure what youre trying to do now, but if you want to use PHP to render it, use echo between PHP opening and closing tags: id="<?php echo 'commentForm' . $row['id']?>". As it is now, I suspect your Javascript is always looking for a form with the literal string 'commentForm' . $row['id']'. row['id'] is not considered a variable.

Next, the syntax of this fetch function looks completely invalid. FormData works nicely with XMLHttpRequest, which I believe is what you're looking for.

For example:

<?php
<script>
    let xhr = new XMLHttpRequest();

    // Your logic for handling the response of the server
    xhr.onreadystatechange = function() {
        if (4 !== this.readyState) {
            // not yet ready
            return;
        }
        if (200 !== this.status) {
            //handle error response
            return;
        }
        // Handle something good...
    }

    xhr.open('POST', 'https://my.page/comment/' + <?php echo $row['id'] ?>);
    xhr.send(new FormData(document.getElementById('myForm')));
</script>
?>

3 Comments

javascript let button = document.getElementById('thatFormButtonId'); button.addEventListener('click', (event) => { event.preventDefault(); // insert AJAX code here }); Not 100% sure if this will also prevent the form itself from submitting. In which case you could do something like: javascript let form = document.getElementById('thatForm'); form.addEventListener('submit', (event) => { event.preventDefault(); // insert AJAX code here });
I get an unexpected identifier error with the first method at this line: javascript let button = document.getElementById('commentB1'); even though commentB1 is the id of the submit button of the form, and that's when I check it with chrome devtools/inspect element.Would send a picture if I could, would be easier to illustrate
In the code above, the ID you give the button is commentB' . $row['id'] . ', which looks very error prone to me. E.g. it has a whitespace as its last character, which might be causing you that error, as 'commentB1' does not have that whitespace. You are right though, would be easier if we could see something more visual.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.