Inserting js alert box in php error

What im trying to do is get any php errors to show as alert boxes instead of loading a page of text showing errors. Im not exactly sure how to go about this due to my ignorance to php but any help would be greatly appreciated.

/* Set e-mail recipient */
$myemail = ",";//"YOUR EMAIL ADDRESS";
/* Check all form inputs using check_input function */
$name = check_input($_POST['name'], "Enter your name");
$email = check_input($_POST['email']);
$message = check_input($_POST['message'], "Write your message");
/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email))
show_error("E-mail address not valid");
/* Let's prepare the message for the e-mail */
$message = "
Name: $name
E-mail: $email
/* Send the message using mail() function */
mail($myemail, "AllenTrey Prod.", $message);
/* Redirect visitor to the thank you page */
header('Location: contact.html');
/* Functions we used */
function check_input($data, $problem='')
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
return $data;
function show_error($myError)
<p>Please correct the following error:</p>
<strong><?php echo $myError; ?></strong>
<p>Hit the back button and try again</p>
1 Like

there’s no alert() in your script.

If you want to alert the users to errors before they submit the form, I think you’ll need to do this in some JavaScript around the form itself. By definition (unless you do it with Ajax) by the time you’ve loaded a PHP script on the server to error-check, it’s going to be outputting a page with something on it. That page could be your form with all the errors highlighted, but if the user made three errors it would be very annoying if that resulted in three alerts when the page is redrawn.

Can you be more specific on when you want the alerts to appear?

ahhh that makes sense ; how would i go about having the form reload with errors? maybe something like this

Yep, that’s the kind of thing. If your PHP code finds an error, have it redraw the original form, with all the boxes filled in (except passwords, probably) and some indication of which boxes you have a problem with. Depending on the layout of the code, you might need to just echo out all the html from the end of your form processing code, or maybe you can call the original form html, pass through the form values and a code that you can use to decide where to show errors.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.