1

I am teaching myself PHP and Ajax. I have created a code where I am trying to send a form through ajax to the PHP server and from the PHP server I am trying to send the same thing back to the client. I am using JSON and vanilla js.

I am trying to use this in vanilla js and I am getting a blank response on the server. I am unable to find how to access this data on the PHP server. I am getting an empty response.

I googled the problem, however, most of those use the jquery serialize method. I want to stay away from jquery for now.

Here is my main js file

//Submits comment to the database
errorMessageDisplay = document.getElementById('error-message');

//When parent form submit button is clicked
document.getElementById("parent_comment_form").addEventListener('submit', function (event) {
    event.preventDefault();

    var poster_name = document.getElementById('poster_name').value;
    var poster_comment = document.getElementById('poster_comment').value;

    //Checks if the poster name or comment is empty
    if (poster_name == '' || poster_comment == ''){
        errorMessageDisplay.innerHTML = "<p style='color: red'>Please Fill in all the Details!</p>";
    } else {

        //Data to be submitted  to server
        //Convert the form data to json string
        var data = {
            "name": poster_name,
            "comment": poster_comment
        };

        //Start of Ajax Request for comments
        var ajaxSubmit = ajaxJSONRequest('submit_comment.php', data);
        ajaxSubmit.onreadystatechange = function () {

            //Prints empty row.
            console.log(ajaxSubmit.responseText);
        }
    }
});

//Creates a new ajax request to avoid repetition of code
function ajaxJSONRequest(url, payloadJSON){
    var ajax = new XMLHttpRequest();
    ajax.open('POST', url, true);
    ajax.setRequestHeader('Content-type', 'application/json');
    ajax.send(JSON.stringify("payload=" + payloadJSON));
    return ajax;
}

Here is my HTML

<head>
    <title>PHP Comments</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>

    <div class="container">
        <h1>Comment App in PHP</h1>

        <form method="post" action="submit_comment.php" id="parent_comment_form">
            <div class="form-control">
                <label for="poster_name">Enter Name:</label>
                <input type="text" name="poster_name" id="poster_name" class="">
            </div>
            <div class="form-control">
                <label for="poster_comment">Enter Comment</label>
                <textarea id="poster_comment" name="poster_comment" ></textarea>
            </div>
            <div class="form-control">
                <button class="btn btn_parent_comment" type="submit" id="submit_form">Submit Comment</button>
            </div>
        </form>
        <div id="error-message"></div>
    </div>

    <script src="main.js"></script>

</body>
</html>

My PHP file is a very basic one: -

<?php

echo json_decode($_POST['payload']);

I am unable to understand how to read these values for inserting values into the database later?

killerprince182
  • 455
  • 2
  • 12
  • @Teemu Than how can I read the values that I have been getting for insertion into DB later? – killerprince182 Jul 08 '21 at 11:31
  • See [how to post and read JSON](https://stackoverflow.com/q/66805555/1169519) to/in PHP. – Teemu Jul 08 '21 at 11:42
  • 1
    `JSON.stringify("payload=" + payloadJSON)` makes no sense, this will not produce valid JSON. Don't get confused between JSON and querystring data formats! Just do `JSON.stringify(payloadJSON)`. And then read [Receive JSON POST with PHP](https://stackoverflow.com/questions/18866571/receive-json-post-with-php) to learn how to write the server-side code correctly, and/or the link Teemu provided. – ADyson Jul 08 '21 at 11:48
  • I tried this. file_get_contents('php://input') shows me data that's in the form already. However, I tried to add new data to the array, not in the form, and then tried this, it didn't show me the data, not in the form. It's still reading POST data, not JSON data. I typed json_decode(file_get_contents("php://input")) which outputted null. – killerprince182 Jul 08 '21 at 11:58
  • 1
    Hmm...it sounds like potentially it's not using AJAX to submit the data. Does your whole page refresh when you do that? – ADyson Jul 08 '21 at 12:01
  • @ADyson The code is in a submit handler, and contains `e.preventDefault()`, though. – Teemu Jul 08 '21 at 12:02
  • 1
    @Teemu true but if the code is included before the form tag in the page, then it won't find anything to attach the event handler to. We can't see the HTML and we can't see the ordering of the scripts and HTML in the page, so we can't verify whether it will actually work as intended or not. – ADyson Jul 08 '21 at 12:03
  • @killerprince182 What _exactly_ did you see when you looked at `file_get_contents('php://input')`? Show us an example, please. And where did you see it - in your main browser screen, or are you viewing it through the browser's developer tools in the network area (in response to an XHR request logged as going to submit_comment.php)? – ADyson Jul 08 '21 at 12:03
  • 2
    @ADyson _“this will not produce valid JSON”_ – don’t see why not, the argument is just a string value, and that can be encoded as JSON perfectly fine. Whether sending the data that way would make much sense, that’d be a different question. – CBroe Jul 08 '21 at 12:05
  • @killerprince182 I'd suggest you to carefully check your new code, and if you can't get it to work, then ask a new question, as you're having a different problem now. – Teemu Jul 08 '21 at 12:05
  • I am getting variables via $_POST[] method normally. However, I want to learn to pass variables via JSON to further my knowledge. I get poster_name=sAS&poster_comment=DASDSADA when I run echo file_get_contents('php://input'); code after submitting the form. I commented preventDefault() to check the error and allow the page to go to the targeted page. I have added the HTML code above. @ADyson – killerprince182 Jul 08 '21 at 12:11
  • @Teemu I just want to receive values from the JSON via AJAX so I can use them for further processing, till now which I am unable to understand :( – killerprince182 Jul 08 '21 at 12:12
  • @killerprince182 If you'll carefully follow the code and instructions in either of the answers in the post I've linked above, you should get your code to work. Both the answers are doing the job (I even tested the code on my local server before posting that answer). – Teemu Jul 08 '21 at 12:17
  • 1
    You've a missunderstanding of how AJAX call works. It doesn't submit the form, or collect the values from the form automatically (or like ADyson suspected, your code is never executed). AJAX sends only, and only the data you pass to it in `send` argument. There are probably better answers for this, but you can read [this my answer](https://stackoverflow.com/a/63509329/1169519), at the end of it there's an example of how to include the form data to an AJAX call. Follow the FormData link in the answer to find out how you can add additional data to your request. – Teemu Jul 08 '21 at 12:28
  • 1
    `I commented preventDefault() to check the error and allow the page to go to the targeted page.`...in that case your test was pointless because it means the Ajax was never executed and JSON was never used. So it doesn't demonstrate anything that you need to know about. Instead of that, use the browser's Developer Tools to see what is happening when you actually run the Ajax call – ADyson Jul 08 '21 at 12:35
  • 1
    @Teemu Thanks for your article. I originally coded the right page, however, my understanding with regard to receiving process was not clear. Now my code is working as I intended. – killerprince182 Jul 08 '21 at 14:34
  • I would like to thank @ADyson for teaching me about the Network tab in the developer console. – killerprince182 Jul 08 '21 at 14:34

0 Answers0