September 26, 2011
Redirecting a page using Javascript, like PHP's Header->Location
Question by Keith Donegan
I have some code like so:
$('.entry a:first').click(function()
{
<?php header("Location:" . "http://www.google.com"); ?>
});
I would like to know how I can achieve this using Javascript.
Answer by Starx
You application of js and php in totally invalid.
You have to understand a fact that JS runs on clientside, once the page loads it does not care, whether the page was a php page or jsp or asp. It executes of DOM and is related to it only.
However you can do something like this
var newLocation = "<?php echo $newlocation; ?>";
window.location = newLocation;
You see, by the time the script is loaded, the above code renders into different form, something like this
var newLocation = "your/redirecting/page.php";
window.location = newLocation;
Like above, there are many possibilities of php and js fusions and one you are doing is not one of them.