Javascript alert inside php is ignored

Hello everybody,
Here is my code:

if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
				echo '<script type="text/javascript">
				       alert("Invalid email address");
				    </script>';
			    header("Location: ../signup.php?signup=email ");
				exit();
			}

The code runs, but when I insert an invalid email, the echo is ignored and jumps to the header()…

Why ?

It probably is showing the alert but you don’t see it as it immediately goes to the sign-up page.

1 Like

Php’s output_buffering is turned on, in the php.ini on your system, causing any output from the php file to be buffered, which is then discarded at the header() statement.

If you put the form and the form processing code on the same page -

  1. It will simplify all the code.
  2. It will allow you to validate all the inputs at once, so that the visitor can correct as many errors as possible at the same time, without needing to repeatedly submit the form to see each next error.
  3. It will allow you to re-populate appropriate form field values so that the visitor doesn’t need to keep entering/selecting values over and over.

The only header() redirect in your form processing code should be upon successful completion of the form processing code, to the exact same url of the current page to cause a get request for that page.

2 Likes

*must be on

If it were not on, PHP wouldnt render the header because something has echoed to the browser before the header call.

The Javascript will never get a chance to activate, because the browser receives the Header first, and acts on it.

I agree with mab here, internalize the processing; and add the fourth thing, which is it will allow you to display the errors on the form, rather than an external page, and allow the user an immediate (from the user’s perspective) reaction.

2 Likes

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