Jerome Durham
Jerome Durham

Reputation: 73

Send form data using JavaScript Fetch and POST and then process it in PHP

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!

Upvotes: 2

Views: 3086

Answers (2)

Jeroen van der Laan
Jeroen van der Laan

Reputation: 724

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>
?>

Upvotes: 1

Ahmed Moayad AlMoghrabi
Ahmed Moayad AlMoghrabi

Reputation: 1277

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;
});

Upvotes: 1

Related Questions