HTML
<form action="https://php.tomgdow.com" method="POST" id="form_one">
<fieldset class="info">
<label for="name">Name</label>
<input type="text" id="name" name="param1">
<span class="msg_name"></span><br>
<label for="textarea" class="space_above">Comment</label><br>
<textarea name="param2" id="textarea" cols="54" rows="10" maxlength="250"
placeholder="Type heref"></textarea>
<input type="submit" class="submit" value="Submit Me!">
</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-choice" class="hidden" id="label-out-choice">
Your comment is </label>
<output for="choice" id="out-choice"></output>
</div>
</fieldset>
<fieldset>
<legend>Server</legend>
<label for="server-response" class="hidden" id="label-server-response">Full Server
Response</label><br>
<output id="server-response"></output>
</fieldset>
</form>
JavaScript
async function sendData() {
const formData = new FormData(form_one);
try {
const response = await fetch("https://php.tomgdow.com", {
method: "POST",
body: formData
});
let result = await response.text();
let responseArray = result.split('&');
document.getElementById('out-name').value = responseArray[0];
document.getElementById('out-choice').value = responseArray[1];
document.getElementById('server-response').value = result;
} catch (e) {
console.error(e);
}
}
const idArray = ["label-out-name", "label-out-choice", "label-server-response",
"out-name", "out-choice", "server-response"];
document.getElementById('form_one').addEventListener('submit', function (event) {
event.preventDefault();
const formData = new FormData(form_one);
if (checkField(event, "name")) {
sendData();
let msg = "Greetings from the PHP Server (POST Method)";
document.getElementById('message').innerText = msg;
for (const key of formData.keys()) {
console.log("%c %s", "color:red", key)
}
for (const elem of idArray) {
document.getElementById(elem).style.visibility = "visible";
}
}
});
document.getElementById('name').addEventListener('focus', function () {
document.getElementsByClassName('msg_name')[0].style.backgroundColor = "white";
document.getElementsByClassName('msg_name')[0].innerText = "";
for (const elem of idArray) {
document.getElementById(elem).style.visibility = "hidden";
}
document.getElementById('name').value = "";
document.getElementById('message').innerText = "";
document.getElementsByTagName('textarea')[0].value = "";
});
php (server)
// index.php (server)
<?php
echo
htmlspecialchars($_POST["param1"])."&"
.htmlspecialchars($_POST["param2"])."&"
.htmlspecialchars($_SERVER['HTTP_HOST']);
?>