1

I have an html form with email address, first name, last name and a checkbox. Everything works fine to post the data to my Postgres database, but now I'm filtering the POST data and I jQuery need to intercept an error from php.

For example, this section of the php program filters email address:

if (empty($_POST["email_field"])) {
    $emailErr = "Email is required";
    echo $emailErr;
} else {
    $email = trim($_POST["email_field"]);
    $email = stripslashes($email);
    $email = htmlspecialchars($email);
    echo 'EMail Filtered ' . $email . '!';
    echo PHP_EOL;
    // check if e-mail address is well-formed
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $emailErr = "Invalid email format";
        echo $emailErr;
        echo PHP_EOL;
        return 1;
    }
}

At the point where the program exists with return 1 when it encounters the email error, I want to show an html message to the end user with "Invalid Email Address" but I'm not clear on how jQuery can get that information.

Here's the jQuery function that fires from the onclick even of the submit button and calls the php function to enter form data into the Postgres database:

<script type="text/javascript">
$("#btn_submit").on("click", function (event) {
    event.preventDefault();
    form_data = $('form').serialize()
    console.log("Okay, I'm starting");
    console.log(form_data);
    console.log("More Info");
    return $.ajax({
        type: "POST",
        url: "collect_data.php",
        data: form_data,
        success: function ( responseText) {
          console.log("Server Reply " + responseText);
        },
        error: function (error) {
          console.log("Server Reply FAIL " + error);
        }
    });
});
</script>

There are a lot of console log messages that do appear in the dev console, but jQuery only gets one. On success, it returns only the first echo message it encounters at the top of the page:

<?php
echo 'Hello ' . htmlspecialchars($_POST["firstname"]) . '!' ;

With the code above, the dev console shows all echo messages up to the point of return, then exits with no error code or anything.

What I need is for the jQuery function get a message from php, but all jQuery shows is an echo of the first line of the program, not any lines below that.

Thanks very much for any help.

EDIT 082119: Per reply from Barmar below, here is the revised code as I have it now, but it doesn't work:

PHP:

$message = '';
$emailErr = '';
if (empty($_POST["email_field"])) {
    $emailErr = "Email is required";
} else {
    $email = trim($_POST["email_field"]);
    $email = stripslashes($email);
    $email = htmlspecialchars($email);
    $message = 'EMail Filtered ' . $email . '!';
    // check if e-mail address is well-formed
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $emailErr = "Invalid email format";
    }
}
  $result = ['success' => empty($emailErr), 'error' => $emailErr,     'message' => $message];
  echo json_encode($result);

HTML:

<script type="text/javascript">
$("#btn_submit").on("click", function (event) {
    event.preventDefault();
    form_data = $('form').serialize()
    console.log("Okay, I'm starting");
    console.log(form_data);
    console.log("More Info");
    return $.ajax({
        type: "POST",
        url: "collect_data.php",
        data: form_data,
        dataType: 'json',
        success: function (response) {
          if (response.success) {
              console.log("Server Reply " + response.message);
          } else {
              console.log("Server error " + response.error);
          }
        },
        error: function (error) {
          console.log("Server Reply FAIL " + error);
        }
    });
});
</script>
1
  • 1
    what happens in the PHP between echo 'Hello ' . htmlspecialchars($_POST["firstname"]) . '!' ; and if (empty($_POST["email_field"])) {? Presumably it finds some reason to exit and not echo anything else. But you didn't show all the code, I think? Commented Aug 20, 2019 at 21:40

1 Answer 1

2

You should have the script send JSON. Then you can structure it so the client can extract the error message.

$message = '';
$emailErr = '';
if (empty($_POST["email_field"])) {
    $emailErr = "Email is required";
} else {
    $email = trim($_POST["email_field"]);
    $email = stripslashes($email);
    $email = htmlspecialchars($email);
    $message = 'EMail Filtered ' . $email . '!';
    // check if e-mail address is well-formed
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $emailErr = "Invalid email format";
    }
}
$result = ['success' => empty($emailErr), 'error' => $emailErr, 'message' => $message];
echo json_encode($result);

The JS checks the success property:

$("#btn_submit").on("click", function (event) {
    event.preventDefault();
    form_data = $('form').serialize()
    console.log("Okay, I'm starting");
    console.log(form_data);
    console.log("More Info");
    return $.ajax({
        type: "POST",
        url: "collect_data.php",
        data: form_data,
        dataType: 'json',
        success: function (response) {
          if (response.success) {
              console.log("Server Reply " + response.message);
          } else {
              console.log("Server error " + response.error);
          }
        },
        error: function (error) {
          console.log("Server Reply FAIL " + error);
        }
    });
});
Sign up to request clarification or add additional context in comments.

11 Comments

Thanks, @Barmar. That really helps to clarify. I just studied your code and it looks like it should solve the problem. I will work on it now. Thanks much.
I just revised the html and php code exactly as you show above, but it fails. My concern is the $result string you have right below the closing brace of the php code -- shouldn't it be above the final enclosing brace? When I researach php $result, it only comes up in the context of MySql, but I use Postgres -- does that make a difference? I'm going to edit my code above to show the code as it is now so you can examine it.
No, it's the correct place. We need to send a result in all cases. Sometimes the result reports success, other times it reports an error.
The code is otherwise the same as yesterday. I would think this would report an error if there was an error in the email address input, and specify that error.
Are there any errors in the JavaScript console? Have you tried using the Network tab of the console to see what's being sent and received?
|

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.