Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript echo'd by PHP doesn't run

I am having a little issue with echoing javascript dynamically via php. Here is my code

$url = "http://www.newsite.com";

echo "
    <html>
    <head>
    <title>Redirecting</title>
    </head>
    <body onload='redirect()'>
        Not Logged In

        <script type = 'text/javascript'>
    function redirect() {
        window.location=".$url."
        }
    </script>
    </body>
    </html>
    ";

My javascript console is telling me that "redirect()" cant be found (Uncaught ReferenceError: redirect is not defined)

Any ideas what's causing this?

like image 274
Esaevian Avatar asked Jan 29 '26 07:01

Esaevian


2 Answers

Drop that client-based redirect entirely. Use:

header("HTTP/1.0 302 Moved Temporarily"); 
header("Location: $url");
like image 175
Tomalak Avatar answered Jan 30 '26 21:01

Tomalak


You're missing a quotation mark. This will fix your issue:

function redirect() {
    window.location='".$url."';
}

Currently, your page is rendered as follows (note the missing quotes / syntax error):

function redirect() {
    window.location=http://www.newsite.com;
}
like image 40
Rob W Avatar answered Jan 30 '26 19:01

Rob W