2

When I submit empty fields, it displays "Something has gone wrong" instead of "All fields are required.". Could you help me to find my mistake please.

PHP file:

<?php 
    if(!isset($_POST['name']) || 
    !isset($_POST['email']) ||
    !isset($_POST['order'])) {
$data = array(
         'message' => "All fields are required."                    
             );
    echo json_encode($data);
    }
?>
2
  • Wtf, you are sending post values and echoing only if post values are missing. So you are logically wrong aren't you? Commented Nov 29, 2015 at 6:57
  • I want to echo if at least one field is missing. It's the first step of validation. Commented Nov 29, 2015 at 8:09

3 Answers 3

2

You conditions in PHP file are wrong. Use this instead

if(isset($_POST['name']) && isset($_POST['email']) && isset($_POST['order'])) {
    $data = array('message' => "Message A");
    echo json_encode($data);
}else{
    $data = array('message' => "All fields are required");
    echo json_encode($data);
}

I use && for required values. You can use && or || according to your need.

Update

if(!isset($_POST['name']) || !isset($_POST['email']) || !isset($_POST['order'])) {
    $data = array('message' => "All fields are required");
    echo json_encode($data);
}else{
    // whatever you want to do, if all values available, goes here
}
Sign up to request clarification or add additional context in comments.

3 Comments

thanks man. but I want to send "all fields are required" message if at least one field is not set.
yes, but my problem is that when i submit empty fields it does not show me "All fields are required" message
empty() does two things. It not only checks if the key exists in $_POST or $_GET but it also checks if it contains a value or not, keep in mind that it considers 0 as empty. isset() only checks if the key exists.
1

Try this:

<?php 
if(!isset($_POST['name']) || !isset($_POST['email']) || !isset($_POST['order'])) {
    echo "No post values found!";
}
else{
    $data = array('message' => "Message A");
    echo json_encode($data);
}
?>

1 Comment

thanks. but my message A is "No post values found" :) so I cannot understand what is wrong with the code.
0

Instead of using !isset() try using empty().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.