0

When I am using JS with PHP i meet a problem

echo '<script type="text/javascript">alert("my alert");</script>';
                        header('Location: /toto.com/');

The JS alert isn't working

Thank you for your help

3
  • Tip: Use Ajax in such cases. Commented Mar 11, 2016 at 12:20
  • I'm not sure exactly what you're trying to achieve here. Display an alert then redirect to another page? At the moment you can't send a header after you've already output something. PHP should tell you headers have already been sent (I think its E_WARNING) Commented Mar 11, 2016 at 12:21
  • it's in a form. I want to alert the member that sth is ok and after redirect on an other page. Ajax seems inapropriate since everything is in PHP exept this tiny part of code Commented Mar 11, 2016 at 12:29

3 Answers 3

2

Javascript is client side language and PHP is server side language so it is executed before your client side code will get executed. Now you are doing like this:

echo '<script type="text/javascript">alert("my alert");</script>';
header('Location: /toto.com/');

Fault

Your PHP script is putting HTML block first and then redirecting it to the location you have mentioned in your header() without giving any chance to your script to be executed.

Code should be like this

echo '<script type="text/javascript">alert("my alert"); window.location.href="/toto.com/";</script>';

This should work...

Sign up to request clarification or add additional context in comments.

1 Comment

I am glad this worked @GromainGillier, just accept this answer as solved, so that it will help others too :)
1

Try this.

echo ("<SCRIPT LANGUAGE='JavaScript'>
           window.alert('Succesfully Updated')
           window.location.href='http://localhost/test1.php';
       </SCRIPT>");

Hope this will work for you..

2 Comments

@SanjayChaudhari this won't work unless you get headers already sent warning
Why are you writing HTML 3.2 this century?
0

Your code is working.. only the header('Location: /toto.com/'); causing the problem.

  echo '<script type="text/javascript">alert("my alert");</script>';
  //header('Location: /toto.com/');

Run the code by commenting the redirection, then you can see the alert message.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.