Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

echo Javascript window.location.href not working

I have a function which echoes javascript to navigate to a different page. While navigation occurs, the

echo 'window.location.href="'.$url.'";'; 

does not work and simply prints it on the screen.

"window.location.href="./index.php";

I use my function this way: redirect("./index.php");

My php function is as follows

  function redirect($url)
   {    
    if (!headers_sent())
    {    
      header('Location: '.$url);
      exit;
    }
   else
    {      
      echo '<script type="text/javascript">';
      echo 'window.location.href="'.$url.'";';
      echo '</script>';
      echo '<noscript>';
      echo '<meta http-equiv="refresh" content="0;url='.$url.'" />';
      echo '</noscript>'; exit;
   }
} 
like image 515
zed Avatar asked Apr 11 '12 18:04

zed


2 Answers

Your browser treats the response as plaintext.

Prepend to you response a Content-Type: text/html\n plus wrap your content inside an <html></html> tag.

like image 171
Peter Aron Zentai Avatar answered Nov 07 '22 21:11

Peter Aron Zentai


Try this way.

<?php
$yourURL="http://www.stackoverflow.com";
echo ("<script>location.href='$yourURL'</script>");
?>
like image 3
Shankar Narayana Damodaran Avatar answered Nov 07 '22 21:11

Shankar Narayana Damodaran