You wrote that you have problems to understand what is happening. So let's look at one of the detailed if statements:
if((empty($_POST['answer1'])) || (trim($_POST['answer1'])=="") || ($_POST['answer1'] == NULL) || (!isset($_POST['answer1']))) { ...
This can be done much easier:
if (empty($_POST['answer1']) || trim($_POST['answer1'])=="") { ...
This is because NULL values are empty() and !isset(...) values are also empty. You have already checked this in the first, so there is no need to check it again.
Then there is no need to add brackets around everything. Add them only when necessary to make the code easier to read.
Change the code based on this:
if (empty($_POST['answer1']) || trim($_POST['answer1'])=="") {$errors = "yes";} if (empty($_POST['answer2']) || trim($_POST['answer2'])=="") {$errors = "yes";} // Error checking, make sure all form fields have input if ($errors == "yes") {
The next part is the $errors variable. There is no need to say yes and no, while your average is true or false . In addition, the variable must be initialized for the case when everything went fine. Let's change the code a bit:
$errors = false; if (empty($_POST['answer1']) || trim($_POST['answer1'])=="") {$errors = true;} if (empty($_POST['answer2']) || trim($_POST['answer2'])=="") {$errors = true;} // Error checking, make sure all form fields have input if ($errors) { // Not all fields were entered error $message = "You must enter values to all of the form fields!"; $output = array('errorsExist' => true, 'message' => $message); }
So now the code looks a little better to find your actual error. To find the error, you need to check which values are actually submitted to your form:
echo '<pre>', htmlspecialchars(print_r($_POST, true)), '</pre>'; die();
Request the page again and you will see what data you sent so that you can check if you are checking the correct fields.
Another method is to expect all messages to have errors. Thus, the default will be true . Then only if all fields are checked, $errors set to false .
So, in your case, if you do not do the correct error checking, your answer will always return errors, even the form in practice. This is why you should control whether your error checks are actually being performed.
According to your comments in the comment, it’s clear that you need to reference the item inside the message fields answer1 and answer2 . You just checked the wrong field.
So just replace $_POST['answer1'] with $_POST['answer1'][2] and the same goes for the other answer. This is the if if example for answer1 :
if (empty($_POST['answer1'][2]) || trim($_POST['answer1'][2])=="") { ... ^^^ ^^^
Just always check the correct variables and it should work as expected.
Related: How to create a request for a server-side script form that has characteristics on the client side?