Skip to content
Advertisement

PHP – unable to echo variables $error and $successMessage

This is a form validation code. I have a bootstrap form but my alerts don’t show up for some reason. My form is here – https://trendingpunjabi.com/test.php.

I am able to do form validation in javascript but want this to work as well.

    $error = ""; $successMessage = "";

    if ($_POST) {
        
//if any of these fields are empty it should show following errors
        if (!$_POST["email"]) {
            $error .= "An email address is required.<br>";
        }
        
        if (!$_POST["content"]) {
            $error .= "The content field is required.<br>";
           }
        
        if (!$_POST["subject"]) {
            $error .= "The subject is required.<br>";
         }
        
        if ($_POST['email'] && filter_var($_POST["email"], FILTER_VALIDATE_EMAIL) === false) {
             $error .= "The email address is invalid.<br>";
             }
        
// This sends the email
        if ($error != "") {
            //bootstrap div for alert
            $error = '<div class="alert alert-danger" role="alert"><p>There were error(s) in your form:</p>' . $error . '</div>';
            
        } else {
              $emailTo = "indian.ranker.jd.com";
              $subject = $_POST['subject'];
              $content = $_POST['content'];
              $headers = "From: ".$_POST['email'];
            
//and if email is sent we should get success message
            if (mail($emailTo, $subject, $content, $headers)) {
                
                $successMessage = '<div class="alert alert-success" role="alert">Your message was sent, we'll get back to you ASAP!</div>';    
            } 
else {
  $error = '<div class="alert alert-danger" role="alert"><p><strong>Your message couldn't be sent - please try again later</div>';
                }
           }
       ** //this is not showing anything **
        echo $error.$successMessage;
        
    }

?>```

Advertisement

Answer

I got my answer from other source. See the text that follows:

“A quick look at the page’s source shows this line:

Which means that line is being sent to the client rather than the php being processed on the server. That will almost certainly be due to using <? rather than <?php

Support for the short form <? is enabled through a setting on the server in .user.ini, generally it’s always wise to use <?php as that is guaranteed to work even if your code moves to another server.”

Thanks

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement