Question

It's the HTML contact form:

<form class="form" method="post" action="mail.php">

     <label for="name">Name:</label>
     <input class="name" type="text" name="name" value="" placeholder="Full Name" required>

      <label for="email">Email:</label>
      <input class="email" type="text" name="email" value="" placeholder="Email" required>

      <label for="message">Message:</label>
      <textarea class="message" rows="4" cols="20" name="message" placeholder="Type..." required></textarea>

      <input type="submit" value="Send">

It's the Ajax I use for my contact form:

$('.form').submit(function() {
var name = $(".name").val();
var email = $(".email").val();
var message = $(".message").val();
var dataString = 'name=' + name + '&email=' + email + '&message=' + message;
$.ajax({
type : "POST",
url : "mail.php",
data : dataString,
cache : false,
success : function() {  
$(".form").hide();
$(".notice").fadeIn(400);
}
});
return false;
});

And it's my mail.php (I found here):

<?php
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
    $email = $_POST['email'];
    $message = $_POST['message'];
    $formcontent="From: $name \n Message: $message";
    $recipient = "example@example.com";
    $subject = "Contact Form";
    $mailheader = "From: $email \r\n";
    mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");

} else {
    header("Location: your_form.html");
}

I just want to add an "Invalid Email Address" message to my form with Ajax (in order to show besides the form, Not in another page)

In the current form when the user submit a filled and valid inputs, it shows a Success message (.notice), but nothing happen when you submit the form with an invalid email address.

Était-ce utile?

La solution

You can try passing arrays from your PHP script back to your AJAX response as data, and let your script handle whatever that is passed back :) In my example below, I have chosen to pass the PHP response back to your AJAX script using the json_encode function, and arbitrarily selected a type of status code that will be read by your JS function to take appropriate action :)

Also, in order your $.ajax to read JSON data correctly, you should include the line dataType: "json" in the function.

Overall, the suggested changes will be:

  1. Echo a response from your PHP script in JSON format using json_encode()
  2. Allows your PHP script to pass the response to your JS script
  3. Ensure that your AJAX function reads the JSON format, and then take the appropriate action

For example, in your PHP script, you can use:

if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
    // If email is valid
    $email = $_POST['email'];
    $message = $_POST['message'];
    $formcontent="From: $name \n Message: $message";
    $recipient = "example@example.com";
    $subject = "Contact Form";
    $mailheader = "From: $email \r\n";

    if(mail($recipient, $subject, $formcontent, $mailheader)) {
        // If mail is sent
        // Status is arbitrary. You can use a string, number... I usually use numbers
        $resp = array("status"=>1, "message"=>"Mail successfully sent.");
    } else {
        // If sending failed
        $resp = array("status"=>2, "message"=>"Error with sending mail.");
    }
} else {
    // If email failed filter check
    $resp = array("status"=>3, "message"=>"You have provided an invalid email address. Please check the email address provided.");
}

// Echos the $resp array in JSON format, which will be parsed by your JS function
echo json_encode($resp);

In your JS file, you can parse the JSON response:

$('.form').submit(function() {
    // Define variables to construct dataString. You don't need to use var to declare each variable individually ;)
    var name = $(".name").val(),
        email = $(".email").val(),
        message = $(".message").val();

    // Construct dataString
    var dataString = 'name=' + name + '&email=' + email + '&message=' + message;

    // Ajax magic
    $.ajax({
        type: "POST",
        url: "mail.php",
        data: dataString,
        dataType: "json",
        cache: false,
        success: function(data) {
            if(data.status == "1") {
                $(".form").hide();
                $(".notice").fadeIn(400);
            } else if (data.status == "2") {
                // Error handling for failure in mail sending
            } else if (data.status == "3") {
                // Error handling for failure in email matching
            } else{
                // Catch all other errors
            }
        }
    });
    return false;
});

Autres conseils

First change your PHP to output Invalid Email Address in case for invalid email address, then check if that message exists as response from ajax:

if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
    $email = $_POST['email'];
    $message = $_POST['message'];
    $formcontent="From: $name \n Message: $message";
    $recipient = "example@example.com";
    $subject = "Contact Form";
    $mailheader = "From: $email \r\n";
    mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
}else{
   echo "Invalid Email Address";
}

And change ajax to:

$('.form').submit(function() {
var name = $(".name").val();
var email = $(".email").val();
var message = $(".message").val();
var dataString = 'name=' + name + '&email=' + email + '&message=' + message;
$.ajax({
type : "POST",
url : "mail.php",
data : dataString,
cache : false,
success : function(data) {
if(data.indexOf("Invalid Email Address") >= 0){
 alert("Invalid Email Address");
}else{
$(".form").hide();
$(".notice").fadeIn(400);
}
}
});
return false;
});

You're going to want to use regular expressions for this, and filter_var. We'll be validating in both Javascript and PHP because the user might not have Javascript enabled.

The regular expressions I normally use to validate emails is this:

[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?

When your forms gets submitted you'll want to run something like this:

var email = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
if(email.test($('.email').val()) === FALSE) {
    $('.notice').html('<strong>Invalid email address!</strong>').show();
    return false;
}

In your PHP once you've checked if the POST request is valid and has all the fields you need you'll want to run filter_var with the FILTER_VALIDATE_EMAIL parameter. filter_var returns a boolean.

if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
    echo 'Invalid email address!';
    exit;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top