Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirecting a page using Javascript, like PHP's Header->Location

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.

like image 274
Keith Donegan Avatar asked Sep 26 '11 17:09

Keith Donegan


People also ask

What is redirect () in PHP?

Redirection from one page to another in PHP is commonly achieved using the following two ways: Using Header Function in PHP: The header() function is an inbuilt function in PHP which is used to send the raw HTTP (Hyper Text Transfer Protocol) header to the client.

How do you redirect the current page to a new URL say Google com'in JavaScript?

You can use the attr() function of jQuery to redirect a web page as shown below: var url = "http://google.com"; $(location). attr('href',url);

How can I redirect a URL to another URL in PHP?

To set a permanent PHP redirect, you can use the status code 301. Because this code indicates an indefinite redirection, the browser automatically redirects the user using the old URL to the new page address.


2 Answers

The PHP code is executed on the server, so your redirect is executed before the browser even sees the JavaScript.

You need to do the redirect in JavaScript too

$('.entry a:first').click(function()
{
    window.location.replace("http://www.google.com");
});
like image 185
klaustopher Avatar answered Sep 21 '22 15:09

klaustopher


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.

like image 39
Starx Avatar answered Sep 20 '22 15:09

Starx