I have a simple contact form with basic php validation, here's the relevant part of code:
$err = '';
if(!preg_match("/^[a-zA-Z ]*$/",$name)) {
$err .= "Name : Only letters and white space allowed.\n";
}
if(strlen($name)<3){
$err .= "Name : Please enter your full name.\n";
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$err .= "Email : Invalid email format.\n";
}
if(strlen($email)<8){
$err .= "Email : Okay, how about using a correct email address?\n";
}
if(strlen($message)<30){
$err .= "Message : Message too short.\n";
}
if($err != ''){
$err = 'There were few errors : \n '.$err;
//THE ALERT BELOW DOESN'T WORKS, gets added into body code, but does not popup
echo '<script type="text/javascript">alert("'.$err.'");</script>';
// While this one works well
//echo '<script type="text/javascript">alert("This alert works. \nThe one above does not.");</script>';
}
else{
//whatever
}
The problem is that the alert()
in the last if condition doesn't work, it gets added in body code but doesn't pop-up. While if I use normal text instead of $err
variable (like the one commented out)- that works all well.
I have had this problem several times in past, I never understood why it happens & what's the solution, I always rather removed the alert and displayed response message normally in a div or something, but this time I need to know - why??