The easiest way to do this is run a XHR request
create this file in PHP for your error script
<?php
// Headers
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Access-Control-Allow-Headers,Content-Type,Access-Control-Allow-Methods, Authorization, X-Requested-With');
if($_POST)
{
echo json_encode($_POST);
// USE this portion if it is a success
//Note weather your data passed or failed you have to respond back to the XHR request in the front end with json_encode...
//Your PHP code
echo json_encode(
array('message' => 'Post Created')
);
}else{
echo json_encode(
array('message' => 'Post Not Created')
);
}
?>
This is the XHR Ajax send with a special method to extract the form values
let xtart = document.getElementById('xhrStart');
xtart.addEventListener('click',function(){console.log('Xstarted')
// First iterate over the form and get all the form Values
var element = {};
var data = new FormData(theForm);
// Display the key/value pairs
for(var pair of data.entries()) {
// console.log(pair[0]+ ', '+ pair[1]);
element[ pair[0].toString() ] = pair[1];
}
console.log(element);
// Time to send the control over to PHP to do its magic
let xhr = new XMLHttpRequest();
xhr.open('POST', 'post.php');
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.responseType = 'json';
xhr.send(JSON.stringify(element));
//xhr.send();
// the response is {"message": "Hello, world!"}
xhr.onload = function() {
let responseObj = xhr.response;
alert(responseObj.message); // Hello, world!
};
});
and example of a html form to invoke the XHR
<form id='theForm'>
<div id="rows">
<div class="sitting-days" style="display:flex; justify-content:center; margin-bottom:20px;">
<div class="select-date" style="margin-right:30px;">
<h4 style="text-align:center;">Select Date</h4>
<input type="date" id="house-sitting-date" name="house_sitting_date" value="">
</div>
<div class="yes-no">
<h4 style="text-align:center;">Yes/No</h4>
<select name="house_sitting_date_yes_no" id="house-yes-no" style="height:24px;">
<option value="nada" selected>Please choose an option</option>
<option value="yes">Yes</option>
</select>
</div>
</div>
</div>
<input type='button' value='Submit' id='xhrStart'>
This is the same method as we use in a rest API and should help your purposes with error and script handling