Reputation: 13275
I am trying to figure out why this form always always returns "Error" when JavaScript is activated, but works like it should when JavaScript is deactivated.
It has something to do with with echo "success"
and echo "error"
, but I really can't find out whats wrong. I tried to echo 1
or 2
, true
or false
- it never works. Why?
My jQuery code:
$("form").submit(function () {
var name = $( "input[name=name]" ),
mail = $( "input[name=email]" ),
message = $( "textarea[name=message]" );
var data = "name=" + name.val() + "&mail=" + mail.val() + "&message=" + encodeURIComponent(message.val());
$.ajax({
url: "my_form.php",
type: "POST",
data: data,
success: function ( data ) {
if ( data == "success" ) {
alert( "Everyhting is good." );
} else {
alert( "Error" );
}
}
});
return false;
})
And the PHP part:
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
function checkEmail( $e ) {
$isValid = true;
if ( strlen( $e ) === 0 ) {
$isValid = false;
}
if ( !preg_match( "/^((?:(?:(?:\w[\.\-\+]?)*)\w)+)\@((?:(?:(?:\w[\.\-\+]?){0,62})\w)+)\.(\w{2,6})$/", $e ) ) {
$isValid = false;
}
if ( $isValid == true ) {
echo "success";
} else {
echo "error";
}
}
checkEmail( $email );
Upvotes: 0
Views: 85
Reputation: 15301
you are calling email mail
in the data string and expecting $_POST['email']
in php.
var data = "name=" + name.val() + "&mail=" + mail.val() + "&message=" + encodeURIComponent(message.val());
change mail
in the line above to email like below.
var data = "name=" + name.val() + "&email=" + mail.val() + "&message=" + encodeURIComponent(message.val());
Upvotes: 2