html
<form action="https://somesite.com" method="POST" id="form_one">
<fieldset class="info">
<legend>Personal Information</legend>
<div>
<label for="name">name</label>
<input type="text" name="param1" id="name">
</div>
<div>
<label for="email">e-mail</label>
<input type="email" name="param2" id="email" required><br>
</div>
<div>
<input type="submit" class="submit">
</div>
</fieldset>
<fieldset class="output">
<legend>Response</legend>
<div id="message"></div>
<div>
<label for="out-name" class="hidden" id="label-out-name">
Your name
</label>
<output for="name" id="out-name"></output>
</div>
<div>
<label for="out-email" class="hidden" id="label-out-email">
Your email address
</label>
<output for="email" id="out-email"></output>
</div>
<div>
<label for="submitted-params" class="hidden" id="label-submitted-params">
Submitted params (POST)
</label><br>
<output for="name email" id="submitted-params"></output>
</div>
</fieldset>
</form>
javascript
document.getElementById('form_one').addEventListener('submit', function (event) {
event.preventDefault();
var param1 = document.getElementById('form_one')[1].value;
var param2 = document.getElementById('form_one')[2].value;
var params = generateParams('param1', param1, 'param2', param2);
console.log("%c %s", "color:green", params)
document.getElementById("submitted-params").value = params;
document.getElementById("label-submitted-params").style.visibility = 'visible';
makePostRequest("https://php.tomgdow.com", params, ajaxCallMe());
});
function makePostRequest(url, params, fn) {
let oReq = new XMLHttpRequest();
oReq.addEventListener("load", fn);
oReq.open('POST', url);
oReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// oReq.setRequestHeader("Content-length", params.length);
// oReq.setRequestHeader("Connection", "close");
oReq.send(params);
}
function ajaxCallMe() {
return function ajax() {
let response = this.responseText;
let message = "Greetings from the PHP Server (POST Method)";
let responseArray = response.split('&');
document.getElementById('out-name').value = responseArray[0];
document.getElementById('out-email').value = responseArray[1];
document.getElementById('message').innerHTML = message;
console.log("%c %s", "color:red", response);
console.log("%c %s", "color:blue", responseArray[0]);
console.log("%c %s", "color:blue", responseArray[1]);
console.log("%c %s", "color:blue", responseArray[2]);
document.getElementById("label-out-name").style.visibility = "visible";
document.getElementById("label-out-email").style.visibility = "visible";
};
}
function generateParams(...args) {
var tmp = "";
if (args.length < 3) { tmp += `${args[0]}=${args[1]}`; } else {
tmp += `${args[0]}=${args[1]}`;
for (let i = 2; i <
args.length; i += 2) { tmp += `&${args[i]}=${args[i + 1]}`; }
}
return tmp;
}
php (server)
// index.php (server)
<?php
echo
htmlspecialchars($_POST["param1"])."&"
.htmlspecialchars($_POST["param2"])."&"
.htmlspecialchars($_SERVER['HTTP_HOST']);
?>