0

I'm trying to make $name, $email, and $message validate in one script without making them all look like a error (make them all a red color) rather than the one that is actually incorrect.

Her is the code I'm using:

PHP:

<?php 
    $name = $_POST['name'];
    $email = $_POST['email'];
    $phone = $_POST['phone'];
    $visitors_site = $_POST['site'];
    $message = $_POST['message'];

    $email_from = 'mattmowen1@gmail.com';
    $email_subject = 'New Contact Submission';

    $to = 'matt.owen@example.com';
    $headers = "From:" . $email;
    $headers = "Contact Submission From: " . $email;
    $message1 = "Name: " . $name;
    $message2 = "\n\nEmail: " . $email;
    $message3 = "\n\nPhone: " . $phone;
    $message4 = "\n\nTheir Site: " . $visitors_site;
    $message5 = "\n\nMessage: " . $message;
    $email_body = $message1 . $message2 . $message3 . $message4 . $message5;

    if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
        mail($to, $email_subject, $email_body,$headers);
        exit(json_encode(array('error' => 0)));
    } else {
        exit(json_encode(array('error' => 1)));
    }

    if ($name == "") {
        exit(json_encode(array('error' => 1)));
    } else {
        mail($to, $email_subject, $email_body,$headers);
        exit(json_encode(array('error' => 0)));
    }
?>

AJAX Script:

var sendEmail = function(){ 
    var url = 'main.php';
    $.ajax({
        url : url,
        type : "POST",
        dataType : "JSON",
        data : $('#contact-form').serialize(),
        success : function(response) {
            if (response.error == 0) { 
                $('#contact-form')[0].reset();
                alert('Form submitted successfully. We will contact you asap.');
            } else {
                $('#email-input').css('color', 'red');
                alert('ERROR MESSAGE');
            }
        }
    })
    return false;
}

HTML:

<div id="contact">
        <div class="container"> 
            <form id="contact-form" method="post" onsubmit="return sendEmail()">
            <h1>Contact Form</h1>
            <fieldset>
                <input placeholder="Your Name" type="text" name="name" id="name-input" required value="<?php echo isset($_POST['name']) ? $_POST['name'] : ''; ?>">
            </fieldset>
            <fieldset>
                <input placeholder="Your Email Address" type="email" name="email" id="email-input" required value="<?php echo isset($_POST['email']) ? $_POST['email'] : ''; ?>">
            </fieldset>
            <fieldset>
                <input placeholder="Your Phone Number (optional)" type="tel" name="phone" required>
            </fieldset>
            <fieldset>
                <input placeholder="Your Web Site (optional)" type="url" name="site" required>
            </fieldset>
            <fieldset>
                <textarea placeholder="Type your message here...." name="message" required value="<?php echo isset($_POST['email']) ? $_POST['email'] : ''; ?>"></textarea>
            </fieldset>
            <fieldset>
                <button type="submit" id="contact-submit" name="submit">Submit</button>
            </fieldset>
            </form>
        </div>
</div>
miken32
  • 42,008
  • 16
  • 111
  • 154
Matt.Owen
  • 391
  • 1
  • 4
  • 15

2 Answers2

3

Just send back a list of bad elements, instead of a blanket error statement

<?php
// ...
$errors = [];
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
    $errors[] = "email";
}

if ($name == "") {
    $errors[] = "name";
}

if ($message == "") {
    $errors[] = "message";
}

if (count($errors) === 0) {
    mail($to, $email_subject, $email_body,$headers);
}
echo json_encode($errors);
//...

Then in your JS:

    success : function(response) {
        if (response.length == 0) { 
            $('#contact-form')[0].reset();
            alert('Form submitted successfully. We will contact you asap.');
        } else {
            for (var i = 0; i < response.length; i++) {
                $('#' + response[i] + '-input').css('color', 'red');
                alert('ERROR MESSAGE');
            }
        }
    }

My Javascript is a bit rusty but that should do the trick.

Note that <textarea> doesn't have a value attribute, contents are added as a child text node. You should also use htmlspecialchars() on all output from PHP to prevent XSS problems.

miken32
  • 42,008
  • 16
  • 111
  • 154
  • The submit button isn't doing anything or the code is wrong. Nothing is happening when I press the submit button – Matt.Owen Apr 04 '17 at 00:13
  • Start looking at standard JS debugging then. Error console etc. Pretty sure no syntax errors got introduced in my code above. – miken32 Apr 04 '17 at 01:52
  • 1
    There were two I saw, you missed a `;` after the message and name error. – Matt.Owen Apr 04 '17 at 21:14
  • Haha I was too busy looking at the JS to notice the basic PHP errors! – miken32 Apr 04 '17 at 21:16
  • Try `echo` instead of `return` in the PHP. This should be the very last line. And make sure nothing else is outputted (including any PHP-error messages). – Mikey Apr 04 '17 at 22:07
  • @Mikey that is working somewhat now. But only the `$name` attribute is changing, `$email` and `$message` stay a black text and how can I limit it to one error popup rather than however many errors there are? – Matt.Owen Apr 04 '17 at 23:20
  • Check your response in your browser's inspector. Are you getting all expected fields? Are the appropriate `id` attributes set on the inputs? JS console showing any errors? – miken32 Apr 04 '17 at 23:22
  • what if I'm using a safari (no inspect element)? EDIT: Nvm you can, one sec – Matt.Owen Apr 04 '17 at 23:22
  • Cmd-Option-I; you may need to enable the "develop" menu in advanced settings. – miken32 Apr 04 '17 at 23:24
  • Yeah, no errors in console. My editor doesn't show any syntax errors or anything. EDIT: I got the `$message` but my `$email` attribute is still not changing color – Matt.Owen Apr 04 '17 at 23:25
  • 1
    Ok. I got it all to work, just needed to add `|| $email == ""` to the `$email` error – Matt.Owen Apr 04 '17 at 23:32
0

in your js:

$erro = 0;
if(document.getElementById("name-input").value == null or document.getElementById("name-input").value == ""){
$erro = 1;
document.getElementById("name-input").style.borderColor = "red";
}
if(document.getElementById("email-input").value == null or document.getElementById("email-input").value == ""){
$erro = 1;
document.getElementById("email-input").style.borderColor = "red";
}
...
if($erro == 0){
//run ajax
}

You can put a bit more html code to make a hidden textbox appear using.

if(document.getElementById("email-input").value == null or document.getElementById("email-input").value == ""){
    $erro = 1;
    document.getElementById("email-input").style.borderColor = "red";
document.getElementById("id_erro1").style.visibility = "visible";
    }    

create in your html:

 <fieldset>
    <input placeholder="Your Email Address" type="email" name="email" id="email-input" required value="<?php echo isset($_POST['email']) ? $_POST['email'] : ''; ?>">
     <input type="hidden" name="error_mensage1" id="id_erro1" value="Required field" >
</fieldset>

Use css to Spice up.

Jose Marques
  • 748
  • 1
  • 6
  • 22