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?