<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>AJAX using post and form to transfer all characters to php page </title>
</head>
<body>
<div align="center">
<!--form id="requestForm"-->
<input type="text" name="fName" id="name"><br>
<input type="text" name="fAddress" id="address"><br>
<input type="text" name="fComment" id="comment"><br>
<button onclick="sendData();" type="button">Submit</button>
<div id="testdiv"></div>
<!--/form-->
</div>
<script>
/*
The FormData interface provides a way to construct a set of key/value pairs representing form fields and their values,
which can be sent using the fetch(), XMLHttpRequest.send() or navigator.sendBeacon() methods.
It uses the same format a form would use if the encoding type were set to "multipart/form-data".
Source:
https://developer.mozilla.org/en-US/docs/Web/API/FormData
https://stackoverflow.com/questions/52646598/send-php-post-using-javascript-ajax
*/
function sendData()
{
var data = new FormData();
data.append('fName', document.getElementById("name").value);
data.append('fAddress', document.getElementById("address").value);
data.append('fComment', document.getElementById("comment").value);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'AJAX_post_get.php', true); // The file to call
xhr.onload = function () {
if(xhr.status !== 200){ // try a file not found error
document.getElementById("testdiv").innerHTML = "Error: "+xhr.status;
return; // Nothing done!
}
document.getElementById("testdiv").innerHTML = this.responseText;
};
xhr.send(data);
}
</script>
</body>
</html>
AJAX_post_get.php
<?php
if($_SERVER['REQUEST_METHOD'] === 'POST') { // not required
var_dump($_POST);
} else {
header('HTTP/1.0 403 Forbidden');
}
?>