POST method to send form data with AJAX without JQUERY
Your first javascript will return error because the data object is not defined.
Try this one
const contactForm = document.getElementById("contact-form");
contactForm.addEventListener("submit", function(event) {
event.preventDefault();
var request = new XMLHttpRequest();
var url = "/php/email-sender.php";
request.open("POST", url, true);
request.setRequestHeader("Content-Type", "application/json");
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200) {
var jsonData = JSON.parse(request.response);
console.log(jsonData);
}
};
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var subject = document.getElementById("subject").value;
var message = document.getElementById("message").value;
var data = JSON.stringify({"name": name, "email": email, "subject": subject, "message": message});
request.send(data);
});
</script>
Check this thread on how to receive json POST: Receive JSON POST with PHP
Then Try this to your PHP file
<?php
// Handling data in JSON format on the server-side using PHP
header("Content-Type: application/json");
// build a PHP variable from JSON sent using POST method
$v = json_decode(stripslashes(file_get_contents("php://input")));
echo json_encode($v);
?>
To access the object in your PHP file, use
$v->name;
$v->email;
$v->subject;
$v->message;
SCREENSHOT: https://s9.postimg.cc/w1fc8266n/2018-05-03_20h37_08.gif