How do I redirect to another webpage?

7 735

2 055

How can I redirect the user from one page to another using jQuery or pure JavaScript?

venkatachalam

Posted 2009-02-02T12:54:16.867

Reputation: 49 117

147I keep seeing both window.location = url; and window.location.href = url; How are they different? Are they? BTW, I didn't know about window.location.replace(url). Nice. – David M. Miller – 2012-06-07T14:24:45.627

100window.location is the same as window.location.href, in terms of behavior. window.location returns an object. If .href is not set, window.location defaults to change the parameter .href. Conclude: Use either one is fine. – Raptor – 2012-08-07T07:03:58.237

10var url = "website name"
$(location).attr('href',url);
– Mad Scientist – 2013-02-18T11:30:19.703

31@MadScientist That is a backwards way to do it. The location object is not a an HTML element and using the jquery object to set it just seems wrong. Why would you use that when the straight JS code is so simple? – Juan Mendes – 2013-11-26T20:25:46.813

1Why do you want to redirect ? The login form should not be submitted? And even if there is no logic in the target page, you still will be able to submit the form to another page. – Dimt – 2014-02-16T14:45:44.927

1JavaScript isn't really too efficient, as JavaScript might be disabled on the client browser. This is why PHP or similar could guarantee a proper redirect. – ascx – 2014-02-25T17:51:07.710

This question asks how to redirect to another page, but the answers including the accepted are talking about how to redirect to a website. – ojonugwa ochalifu – 2014-05-12T23:20:17.220

@OjonugwaOchalifu you can add a relative or absolute url if you like (instead of a website url) – Adrien Be – 2014-06-20T08:46:47.080

Refer this Link

– KarSho – 2015-04-12T02:45:21.603

1

Video showing all the approaches: https://www.youtube.com/watch?v=CkLSapxVyGQ

– ssmith – 2016-11-13T14:43:37.443

1don't forget to call return false if its done in a javascript client event otherwise you won't be redirected. – Herman Van Der Blom – 2017-11-20T13:58:14.650

Answers

13 390

One does not simply redirect using jQuery

jQuery is not necessary, and window.location.replace(...) will best simulate an HTTP redirect.

window.location.replace(...) is better than using window.location.href, because replace() does not keep the originating page in the session history, meaning the user won't get stuck in a never-ending back-button fiasco.

If you want to simulate someone clicking on a link, use location.href

If you want to simulate an HTTP redirect, use location.replace

For example:

// similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");

// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";

Ryan McGeary

Posted 2009-02-02T12:54:16.867

Reputation: 186 708

58in case of submit button add return false ; also inside your function – Abhi – 2012-04-19T11:52:02.413

114The question is about javascript specifically, but it may be worth noting that a meta refresh can be used as a fail back in case the user has javascript disabled – Hoppe – 2013-01-24T00:51:34.643

17@NicolòMartini If(IE) document.write(""); – Jeff Noel – 2013-06-07T13:28:29.053

2

yes it works: http://jsfiddle.net/NcB2w/2/show/

– Stano – 2013-06-14T10:28:57.257

1Why do we never get explicit with document but it's always window.location or window.open? Properties of window are global. – Erik Reppen – 2013-06-16T02:55:14.807

1What would be the practical difference? @RyanMcGeary – Pinch – 2013-06-17T18:19:51.530

1

this didn't work for my scenario but this did : http://stackoverflow.com/questions/12591953/redirect-to-other-page-on-alert-box-confirm

– null – 2013-08-11T10:02:23.287

2What code can I use so the redirect works in production and development? Because the domain differs of course – user1529956 – 2013-12-06T17:15:29.260

1

@NicolòMartini this is how I work around the referrer issue, also it gives me a nice tidy way to abstract site navigation logic away https://github.com/michaelpapworth/jQuery.navigate

– Michael Papworth – 2014-01-13T10:38:43.030

34If you're already using jQuery, just use $(location).attr('href',url);. window.location.href seems to have inconstant behavior in some browsers, in fact, it flat out doesn't work in my version of Firefox. I've heard tell of setting window.location directly not working in versions of IE. – Noz – 2015-01-28T22:34:13.960

2There is an issue with this code, because the same code doesn't work when you go back using the back button. It just doesn't work anymore. – victor sosa – 2015-03-31T20:45:07.213

3@Samir, No. The correct answer is to call the window.location.replace(...) function -- something that jQuery can't help improve. Pedantic commentary on a 6 year-old vetted answer isn't appreciated. – Ryan McGeary – 2015-09-07T14:25:16.103

1@RyanMcGeary When using window.location.replace(), can I only add the directory, or must I include the host? – Jacques Marais – 2015-09-24T15:56:55.267

1@JacquesMarais Yes, relative and absolute paths should both work. Just like the href attribute in an anchor tag <a>. – Ryan McGeary – 2015-09-24T20:22:33.947

2"is better" should be removed. As stated later in the answer, the best solution is situational. OP does not ask "how can I emulate an HTTP redirect with Javascript..." – MadMaardigan – 2017-03-23T15:35:45.353

3Does not work if a link begins with www. It does only work with http or https. But how can we make sure that the website even supports https?! – Black – 2017-09-14T15:03:58.113

1

See demo @ http://www.jquerypot.com/how-to-redirect-the-user-from-one-page-to-another-in-jquery/

– Ketan Savaliya – 2018-04-09T07:57:32.403

1

Thats incorrect, you CAN redirect. Look here: https://stackoverflow.com/a/19036954/4684797

– Black – 2018-04-20T07:46:44.170

1Why not just use a Location header? – ytpillai – 2018-05-15T21:12:59.617

1Excellent! Using replace is the only way around the "Headers already sent" error. It solves all kinds of problems with output buffering and timely progress reporting. I used it inside a recursive AJAX loop to report the progress, then forward to another page when finished. – Bob Ray – 2018-06-05T05:23:59.503

1Although I've used and still use jQuery for many projects, whenever I had to redirect the page, I've always used window.location.*. In my opinion, when we us JavaScript, we should use the built-in methods, if they are available and properly implemented. – user7637745 – 2018-06-15T08:25:38.970

@Hoppe, who disables JavaScript nowadays? – Lamy – 2018-11-23T16:23:52.147

@Lamy, I guess I should have phrased it differently. Ie, technically you don't even need JavaScript to redirect. I do also wonder if there are any accessibility programs that disable JS, – Hoppe – 2018-11-24T04:24:15.830

1 526

WARNING: This answer has merely been provided as a possible solution; it is obviously not the best solution, as it requires jQuery. Instead, prefer the pure JavaScript solution.

$(location).attr('href', 'http://stackoverflow.com')

Boris Guéry

Posted 2009-02-02T12:54:16.867

Reputation: 40 407

51This is that literal answer to the question. If you are already using Jquery and therefore have it already loaded then it will be more bandwidth efficient and of course clearer to use the shortcut – barrymac – 2012-01-12T12:00:40.080

22More importantly, is there a way to do this with jQuery that is absracted? This is just a wrapper for window.location.href = url; But if jQuery had some function that, if window.location.href = url; wasn't going to work in the current environment (browser, OS, etc.) jQuery core could compensate? – Chris – 2012-02-29T16:03:25.863

240Forcing jQuery into the equation in this way is just ridiculous and pointless, especially since window.location is not an element and therefore does not have attributes. – Tim Down – 2012-10-03T10:32:36.370

1I think window.location does not work on some IE versions.The point of jQuery is not just easing front end scripting but making it cross browser too. – Mad Scientist – 2013-02-18T12:08:28.093

8I somehow doubt this still works with recent jQuery versions where .attr() actually sets attributes (i.e. .setAttribute()) – ThiefMaster – 2013-07-03T11:23:52.673

131

@deltaray This is not another way to redirect, like said above, it's a meaningless wrapper around the location object, which, is not even an element! This reminds me of http://i.stack.imgur.com/ssRUr.gif

– JCM – 2014-01-23T15:48:46.817

4also $(location)[0].href = url; and even $, location.href = url; I prefer second jQuery solution – vp_arth – 2014-04-04T20:06:58.753

2I know it is an old question, there is a curiosity: some XSS filters don't allow things like <script>location="http://example.com;</script>" and will block it, but if you use jQuery they will not block it. – Gustavo Rodrigues – 2014-08-11T20:06:16.683

4No need for the warning, the OP asked for a JQ answer, and so he/she shall receive. – Ben – 2014-10-12T01:05:18.110

3jQuery will at least take care of any cross-browser compatibility issues with the different JavaScript APIs. – Henry Heleine – 2014-12-09T21:50:28.210

6Why on earth would you ever do this. JQuery is meant as a DOM manipulation library. Not for this. This solution is a bad solution. The OP asked for JQuery and the answer should be to tell the OP that JQuery is not needed and not used for this. The right tool for the right job. JQuery is great for DOM but should not be forced to do things its not meant to do. – Patrick W. McMahon – 2015-11-18T21:54:00.420

6This is a really, really bad answer and I'm stunned by the number of votes it has received. The attr() method is used for setting attribute values on DOM objects. Using it for this is counter to the intention of the method and thus you cannot possibly guarantee that this method will work in the future. – Nick Coad – 2016-01-13T05:55:38.620

2As the location object is supported in literally every browser in use today, there's no way using jQuery will make this code more "cross-browser" – rvighne – 2016-07-12T22:40:17.107

2People, maybe jQuery it is not required to redirect. Maybe jQuery is NOT the Right Way™ to redirect. Maybe OP didn't really mean jQuery, just Javascript. But the fact is you can redirect with jQuery and if, for any reason, you want to do it, this is the (kinda hacky) way to do it. I think that this answer, warning included is the best way to answer this question as it is stated. – xDaizu – 2016-08-26T09:02:35.660

IF you use jQuery for this, use .prop() , because of what @Tim Down said :-) – jave.web – 2016-12-12T12:28:37.107

1Actually the question is how to makeit with JQUERY, not how to do it on plain vanilla javascript. This should be the answer. – moplin – 2017-05-04T17:15:20.880

4If you know exactly what jQuery does you know it literally is doing a million operations just to set "location.href". This is not browser cross-compatible, it does not save bandwidth. But if you want a run through of what happens: 1) $() is a function that wraps, arrays and objects, and things in the DOM (what it's meant for), In this case 'location' is a object. "attr" sets a certain key on that object, after going another million operations. None of those operations include browser checks for this case because no such thing exists. It's just a waste to set an object's property. – kezi – 2017-10-09T13:41:34.757

543

Standard "vanilla" JavaScript way to redirect a page:

window.location.href = 'newPage.html';


If you are here because you are losing HTTP_REFERER when redirecting, keep reading:


The following section is for those using HTTP_REFERER as one of many secure measures (although it isn't a great protective measure). If you're using Internet Explorer 8 or lower, these variables get lost when using any form of JavaScript page redirection (location.href, etc.).

Below we are going to implement an alternative for IE8 & lower so that we don't lose HTTP_REFERER. Otherwise you can almost always simply use window.location.href.

Testing against HTTP_REFERER (URL pasting, session, etc.) can be helpful in telling whether a request is legitimate. (Note: there are also ways to work-around / spoof these referrers, as noted by droop's link in the comments)


Simple cross-browser testing solution (fallback to window.location.href for Internet Explorer 9+ and all other browsers)

Usage: redirect('anotherpage.aspx');

function redirect (url) {
    var ua        = navigator.userAgent.toLowerCase(),
        isIE      = ua.indexOf('msie') !== -1,
        version   = parseInt(ua.substr(4, 2), 10);

    // Internet Explorer 8 and lower
    if (isIE && version < 9) {
        var link = document.createElement('a');
        link.href = url;
        document.body.appendChild(link);
        link.click();
    }

    // All other browsers can use the standard window.location.href (they don't lose HTTP_REFERER like Internet Explorer 8 & lower does)
    else { 
        window.location.href = url; 
    }
}

Mark Pieszak - DevHelp.Online

Posted 2009-02-02T12:54:16.867

Reputation: 26 262

52

Foot note: checking for referrer as a security measure is a lousy solution. https://duckduckgo.com/?q=referrer+spoofing

– droope – 2013-01-29T23:41:11.123

If you have an HTTP GET session ID in the referrer URL it can be used to check that against the session for validity. – Andrew Fox – 2015-08-21T04:31:05.037

@mcpDESIGNS are you sure that you've tried to use location.assign? I use in my app with IE8, and I don't lose the HTTP_REFERER header. – Buzinas – 2015-09-30T18:35:27.693

At least back in 2012 it wasn't working, maybe later patches of IE8 fixed it - that's good to hear though! – Mark Pieszak - DevHelp.Online – 2018-02-26T00:41:47.633

363

Use:

// window.location
window.location.replace('http://www.example.com')
window.location.assign('http://www.example.com')
window.location.href = 'http://www.example.com'
document.location.href = '/path'

// window.history
window.history.back()
window.history.go(-1)

// window.navigate; ONLY for old versions of Internet Explorer
window.navigate('top.jsp')


// Probably no bueno
self.location = 'http://www.example.com';
top.location = 'http://www.example.com';

// jQuery
$(location).attr('href','http://www.example.com')
$(window).attr('location','http://www.example.com')
$(location).prop('href', 'http://www.example.com')

Govind Singh

Posted 2009-02-02T12:54:16.867

Reputation: 9 975

7window.navigate is old-IE-only (Firefox/Chrome do not support this). If you want to enumerate all options, don't forget about document.location. – Rob W – 2014-11-26T18:19:10.067

118This does not explain anything at all. What is someone supposed to pick? Pick one randomly from the list? Also, what does this add to the existing answers? – Léo Lam – 2015-07-17T07:13:15.673

document.location = document.referrer;

Please add it in list also. This does not work like History.back rather makes the page Refresh again. – Ali Humayun – 2015-07-30T20:22:46.557

.attr() will not work on jQuery 3.0.0. use .val() instead. – Rivalus – 2016-06-19T20:41:21.467

2@LéoLam That's why there is a search engine called Google. :-) You can search each each one on Google and find the difference. You don't want to pick one randomly. – I am the Most Stupid Person – 2017-09-18T10:43:02.007

7@IamtheMostStupidPerson exactly my point. The answer is useless. – Léo Lam – 2017-09-18T10:44:23.373

You could see docs too, https://developer.mozilla.org/en-US/docs/Web/API/Location

– John Balvin Arias – 2018-05-25T10:12:24.320

285

This works for every browser:

window.location.href = 'your_url';

Fred

Posted 2009-02-02T12:54:16.867

Reputation: 2 891

3You could also do document.location.replace(redirectURL) if you don't want the first page to be in the browser history – jazzcat – 2018-06-12T14:06:41.627

268

It would help if you were a little more descriptive in what you are trying to do. If you are trying to generate paged data, there are some options in how you do this. You can generate separate links for each page that you want to be able to get directly to.

<a href='/path-to-page?page=1' class='pager-link'>1</a>
<a href='/path-to-page?page=2' class='pager-link'>2</a>
<span class='pager-link current-page'>3</a>
...

Note that the current page in the example is handled differently in the code and with CSS.

If you want the paged data to be changed via AJAX, this is where jQuery would come in. What you would do is add a click handler to each of the anchor tags corresponding to a different page. This click handler would invoke some jQuery code that goes and fetches the next page via AJAX and updates the table with the new data. The example below assumes that you have a web service that returns the new page data.

$(document).ready( function() {
    $('a.pager-link').click( function() {
        var page = $(this).attr('href').split(/\?/)[1];
        $.ajax({
            type: 'POST',
            url: '/path-to-service',
            data: page,
            success: function(content) {
               $('#myTable').html(content);  // replace
            }
        });
        return false; // to stop link
    });
});

tvanfosson

Posted 2009-02-02T12:54:16.867

Reputation: 421 512

227

I also think that location.replace(URL) is the best way, but if you want to notify the search engines about your redirection (they don't analyze JavaScript code to see the redirection) you should add the rel="canonical" meta tag to your website.

Adding a noscript section with a HTML refresh meta tag in it, is also a good solution. I suggest you to use this JavaScript redirection tool to create redirections. It also has Internet Explorer support to pass the HTTP referrer.

Sample code without delay looks like this:

<!-- Place this snippet right after opening the head tag to make it work properly -->

<!-- This code is licensed under GNU GPL v3 -->
<!-- You are allowed to freely copy, distribute and use this code, but removing author credit is strictly prohibited -->
<!-- Generated by http://insider.zone/tools/client-side-url-redirect-generator/ -->

<!-- REDIRECTING STARTS -->
<link rel="canonical" href="https://yourdomain.com/"/>
<noscript>
    <meta http-equiv="refresh" content="0;URL=https://yourdomain.com/">
</noscript>
<!--[if lt IE 9]><script type="text/javascript">var IE_fix=true;</script><![endif]-->
<script type="text/javascript">
    var url = "https://yourdomain.com/";
    if(typeof IE_fix != "undefined") // IE8 and lower fix to pass the http referer
    {
        document.write("redirecting..."); // Don't remove this line or appendChild() will fail because it is called before document.onload to make the redirect as fast as possible. Nobody will see this text, it is only a tech fix.
        var referLink = document.createElement("a");
        referLink.href = url;
        document.body.appendChild(referLink);
        referLink.click();
    }
    else { window.location.replace(url); } // All other browsers
</script>
<!-- Credit goes to http://insider.zone/ -->
<!-- REDIRECTING ENDS -->

Patartics Milán

Posted 2009-02-02T12:54:16.867

Reputation: 3 542

201

But if someone wants to redirect back to home page then he may use the following snippet.

window.location = window.location.host

It would be helpful if you have three different environments as development, staging, and production.

You can explore this window or window.location object by just putting these words in Chrome Console or Firebug's Console.

Nadeem Yasin

Posted 2009-02-02T12:54:16.867

Reputation: 3 414

window.location.replace(window.location.protocol + "//" + window.location.host) – moala – 2014-01-17T00:21:28.603

12even simpler: window.location = '/' – Iftah – 2014-06-21T23:56:02.187

4Iftah - that is dependant on the "base" meta tag. – Rob Quist – 2016-01-26T13:18:59.653

191

JavaScript provides you many methods to retrieve and change the current URL which is displayed in browser's address bar. All these methods uses the Location object, which is a property of the Window object. You can create a new Location object that has the current URL as follows..

var currentLocation = window.location;

Basic Structure of a URL

<protocol>//<hostname>:<port>/<pathname><search><hash>

enter image description here

  1. Protocol -- Specifies the protocol name be used to access the resource on the Internet. (HTTP (without SSL) or HTTPS (with SSL))

  2. hostname -- Host name specifies the host that owns the resource. For example, www.stackoverflow.com. A server provides services using the name of the host.

  3. port -- A port number used to recognize a specific process to which an Internet or other network message is to be forwarded when it arrives at a server.

  4. pathname -- The path gives info about the specific resource within the host that the Web client wants to access. For example, stackoverflow.com/index.html.

  5. query -- A query string follows the path component, and provides a string of information that the resource can utilize for some purpose (for example, as parameters for a search or as data to be processed).

  6. hash -- The anchor portion of a URL, includes the hash sign (#).

With these Location object properties you can access all of these URL components

  1. hash -Sets or returns the anchor portion of a URL.
  2. host -Sets or returns the hostname and port of a URL.
  3. hostname -Sets or returns the hostname of a URL.
  4. href -Sets or returns the entire URL.
  5. pathname -Sets or returns the path name of a URL.
  6. port -Sets or returns the port number the server uses for a URL.
  7. protocol -Sets or returns the protocol of a URL.
  8. search -Sets or returns the query portion of a URL

Now If you want to change a page or redirect the user to some other page you can use the href property of the Location object like this

You can use the href property of the Location object.

window.location.href = "http://www.stackoverflow.com";

Location Object also have these three methods

  1. assign() -- Loads a new document.
  2. reload() -- Reloads the current document.
  3. replace() -- Replaces the current document with a new one

You can use assign() and replace methods also to redirect to other pages like these

location.assign("http://www.stackoverflow.com");

location.replace("http://www.stackoverflow.com");

How assign() and replace() differs -- The difference between replace() method and assign() method(), is that replace() removes the URL of the current document from the document history, means it is not possible to use the "back" button to navigate back to the original document. So Use the assign() method if you want to load a new document, andwant to give the option to navigate back to the original document.

You can change the location object href property using jQuery also like this

$(location).attr('href',url);

And hence you can redirect the user to some other url.

Nikhil Agrawal

Posted 2009-02-02T12:54:16.867

Reputation: 16 632

175

Should just be able to set using window.location.

Example:

window.location = "https://stackoverflow.com/";

Here is a past post on the subject:

How do I redirect to another webpage?

Newse

Posted 2009-02-02T12:54:16.867

Reputation: 2 060

It maybe works, but I am not sure if this the right way to do it. I'm not see documentation that support this. It could leads programmers to a bad programming practices. – Jaider – 2016-11-11T20:25:22.673

159

Basically jQuery is just a JavaScript framework and for doing some of the things like redirection in this case, you can just use pure JavaScript, so in that case you have 3 options using vanilla JavaScript:

1) Using location replace, this will replace the current history of the page, means that it is not possible to use the back button to go back to the original page.

window.location.replace("http://stackoverflow.com");

2) Using location assign, this will keep the history for you and with using back button, you can go back to the original page:

window.location.assign("http://stackoverflow.com");

3) I recommend using one of those previous ways, but this could be the third option using pure JavaScript:

window.location.href="http://stackoverflow.com";

You can also write a function in jQuery to handle it, but not recommended as it's only one line pure JavaScript function, also you can use all of above functions without window if you are already in the window scope, for example window.location.replace("http://stackoverflow.com"); could be location.replace("http://stackoverflow.com");

Also I show them all on the image below:

location.replace location.assign

Alireza

Posted 2009-02-02T12:54:16.867

Reputation: 43 514

152

Before I start, jQuery is a JavaScript library used for DOM manipulation. So you should not be using jQuery for a page redirect.

A quote from Jquery.com:

While jQuery might run without major issues in older browser versions, we do not actively test jQuery in them and generally do not fix bugs that may appear in them.

It was found here: https://jquery.com/browser-support/

So jQuery is not an end-all and be-all solution for backwards compatibility.

The following solution using raw JavaScript works in all browsers and have been standard for a long time so you don't need any libraries for cross browser support.

This page will redirect to Google after 3000 milliseconds

<!DOCTYPE html>
<html>
    <head>
        <title>example</title>
    </head>
    <body>
        <p>You will be redirected to google shortly.</p>
        <script>
            setTimeout(function(){
                window.location.href="http://www.google.com"; // The URL that will be redirected too.
            }, 3000); // The bigger the number the longer the delay.
        </script>
    </body>
</html>

Different options are as follows:

window.location.href="url"; // Simulates normal navigation to a new page
window.location.replace("url"); // Removes current URL from history and replaces it with a new URL
window.location.assign("url"); // Adds new URL to the history stack and redirects to the new URL

window.history.back(); // Simulates a back button click
window.history.go(-1); // Simulates a back button click
window.history.back(-1); // Simulates a back button click
window.navigate("page.html"); // Same as window.location="url"

When using replace, the back button will not go back to the redirect page, as if it was never in the history. If you want the user to be able to go back to the redirect page then use window.location.href or window.location.assign. If you do use an option that lets the user go back to the redirect page, remember that when you enter the redirect page it will redirect you back. So put that into consideration when picking an option for your redirect. Under conditions where the page is only redirecting when an action is done by the user then having the page in the back button history will be okay. But if the page auto redirects then you should use replace so that the user can use the back button without getting forced back to the page the redirect sends.

You can also use meta data to run a page redirect as followed.

META Refresh

<meta http-equiv="refresh" content="0;url=http://evil.com/" />

META Location

<meta http-equiv="location" content="URL=http://evil.com" />

BASE Hijacking

<base href="http://evil.com/" />

Many more methods to redirect your unsuspecting client to a page they may not wish to go can be found on this page (not one of them is reliant on jQuery):

https://code.google.com/p/html5security/wiki/RedirectionMethods

I would also like to point out, people don't like to be randomly redirected. Only redirect people when absolutely needed. If you start redirecting people randomly they will never go to your site again.

The next part is hypothetical:

You also may get reported as a malicious site. If that happens then when people click on a link to your site the users browser may warn them that your site is malicious. What may also happen is search engines may start dropping your rating if people are reporting a bad experience on your site.

Please review Google Webmaster Guidelines about redirects: https://support.google.com/webmasters/answer/2721217?hl=en&ref_topic=6001971

Here is a fun little page that kicks you out of the page.

<!DOCTYPE html>
<html>
    <head>
        <title>Go Away</title>
    </head>
    <body>
        <h1>Go Away</h1>
        <script>
            setTimeout(function(){
                window.history.back();
            }, 3000);
        </script>
    </body>
</html>

If you combine the two page examples together you would have an infant loop of rerouting that will guarantee that your user will never want to use your site ever again.

Patrick W. McMahon

Posted 2009-02-02T12:54:16.867

Reputation: 2 378

5I address his request for jQuery by saying it's not needed. JQuery has a lot of great useful shortcuts for JavaScript but there is no need for any shortcuts for redirects. JQuery is just JavaScript. Nothing more. The normal way to call a redirect will work with his functions using jQuery. – Patrick W. McMahon – 2015-06-27T12:16:27.297

Patrick, by your own logic there is no need for JQuery in all situations. The whole point is convenience, and the question asked for it. The best tool I'd say is the JQuery version because it will probably abstract away browser specifics for the future. So your argument is still null and void. The question asked for JQuery. – Epirocks – 2015-06-30T22:17:17.420

You may be right about that currently, however you are not able to see the future and cannot at this time predict how future proof it is. And the fact remains the question asked for JQuery! – Epirocks – 2015-07-02T22:19:42.440

"Yeah JavaScript could change and if it changes then jQuery then needs to change as jQuery is JavaScript. – Patrick W. McMahon yesterday" Thankyou, I rest my case. – Epirocks – 2015-07-05T18:45:26.073

You have no case. JQuery has a higher chance to change then JavaScript. New version of JQuery get realest all the time and old jQuery becomes obsolete and them makes problems will code reliant on a set version of JQuery. – Patrick W. McMahon – 2015-07-05T18:50:59.560

JQuery frequently breaks from version to version. Many drupal and wordpress plugins often only work with set jQuery version's and will not work with newer ones. – Patrick W. McMahon – 2015-07-05T19:12:53.473

Multiple jQuery version's have changed everything about jQuery and was not backwards compatible – Patrick W. McMahon – 2015-07-05T19:14:27.130

Hence keeping up-to-date with the latest one. 1.9 was a big one, the breaking changes are documented. Version 2.0 don't like IE 8 and lower, and quite rightly so. So it depends what you mean by broken. Changes are to get JQuery onto a better path and better able to handle changes. – Epirocks – 2015-07-05T19:33:38.137

JQuery has changed and has had version problems so based on it's past you can't say it will not happen again. – Patrick W. McMahon – 2015-07-05T19:37:52.910

148

var url = 'asdf.html';
window.location.href = url;

user188973

Posted 2009-02-02T12:54:16.867

Reputation:

133

You can do that without jQuery as:

window.location = "http://yourdomain.com";

And if you want only jQuery then you can do it like:

$jq(window).attr("location","http://yourdomain.com");

ScoRpion

Posted 2009-02-02T12:54:16.867

Reputation: 7 118

JQuery is arguably a better idea as it could abstract away future browser changes/deprecations – Epirocks – 2015-06-24T23:14:27.050

132

This works with jQuery:

$(window).attr("location", "http://google.fr");

xloadx

Posted 2009-02-02T12:54:16.867

Reputation: 1 393

79

# HTML Page Redirect Using jQuery/JavaScript

Try this example code:

function YourJavaScriptFunction()
{
    var i = $('#login').val();
    if (i == 'login')
        window.location = "login.php";
    else
        window.location = "Logout.php";
}

If you want to give a complete URL as window.location = "www.google.co.in";.

Sakthi Karthik

Posted 2009-02-02T12:54:16.867

Reputation: 1 928

"Using jQuery" is um, inaccurate. And the example of using a complete URL won't work, as that's not a complete URL. There's no protocol, so it'll be interpreted as a relative URL. – 1j01 – 2017-10-31T21:18:27.813

73

So, the question is how to make a redirect page, and not how to redirect to a website?

You only need to use JavaScript for this. Here is some tiny code that will create a dynamic redirect page.

<script>
    var url = window.location.search.split('url=')[1]; // Get the URL after ?url=
    if( url ) window.location.replace(url);
</script>

So say you just put this snippet into a redirect/index.html file on your website you can use it like so.

http://www.mywebsite.com/redirect?url=http://stackoverflow.com

And if you go to that link it will automatically redirect you to stackoverflow.com.

Link to Documentation

And that's how you make a Simple redirect page with JavaScript

Edit:

There is also one thing to note. I have added window.location.replace in my code because I think it suits a redirect page, but, you must know that when using window.location.replace and you get redirected, when you press the back button in your browser it will not got back to the redirect page, and it will go back to the page before it, take a look at this little demo thing.

Example:

The process: store home => redirect page to google => google

When at google: google => back button in browser => store home

So, if this suits your needs then everything should be fine. If you want to include the redirect page in the browser history replace this

if( url ) window.location.replace(url);

with

if( url ) window.location.href = url;

iConnor

Posted 2009-02-02T12:54:16.867

Reputation: 14 324

71

You need to put this line in your code:

$(location).attr("href","http://stackoverflow.com");

If you don't have jQuery, go JavaScript with:

window.location.replace("http://stackoverflow.com");
window.location.href("http://stackoverflow.com");

Ashish Ratan

Posted 2009-02-02T12:54:16.867

Reputation: 2 276

what the point of wrapping everything in jquery? – ruX – 2016-09-22T18:12:41.303

68

On your click function, just add:

window.location.href = "The URL where you want to redirect";
$('#id').click(function(){
    window.location.href = "http://www.google.com";
});

Swaprks

Posted 2009-02-02T12:54:16.867

Reputation: 1 299

62

*****THE ORIGINAL QUESTION WAS - "HOW TO REDIRECT USING JQUERY", HENCE THE ANSWER IMPLEMENTS JQUERY >> COMPLIMENTARY USAGE CASE*****

To just redirect to a page with JavaScript:

  window.location.href = "/contact/";

Or if you need a delay:

setTimeout(function () {
  window.location.href = "/contact/";
}, 2000);   // Time in milliseconds

jQuery allows you to select elements from a web page with ease. You can find anything you want on a page and then use jQuery to add special effects, react to user actions, or show and hide content inside or outside the element you have selected. All these tasks start with knowing how to select an element or an event.

     $('a,img').on('click',function(e){
         e.preventDefault();
         $(this).animate({
             opacity: 0 //Put some CSS animation here
         }, 500);
         setTimeout(function(){
           // OK, finished jQuery staff, let's go redirect
           window.location.href = "/contact/";
         },500);
     });

Imagine someone wrote a script/plugin that is 10000 lines of code?! Well, with jQuery you can connect to this code with just a line or two.

SergeDirect

Posted 2009-02-02T12:54:16.867

Reputation: 1 018

It is preferable not to write in caps, although good answer – cnexans – 2018-10-12T19:55:31.760

56

Try this:

location.assign("http://www.google.com");

Code snippet of example.

tilak

Posted 2009-02-02T12:54:16.867

Reputation: 2 778

52

jQuery is not needed. You can do this:

window.open("URL","_self","","")

It is that easy!

The best way to initiate an HTTP request is with document.loacation.href.replace('URL').

MayorMonty

Posted 2009-02-02T12:54:16.867

Reputation: 3 141

49

First write properly. You want to navigate within an application for another link from your application for another link. Here is the code:

window.location.href = "http://www.google.com";

And if you want to navigate pages within your application then I also have code, if you want.

Anup

Posted 2009-02-02T12:54:16.867

Reputation: 2 639

49

You can redirect in jQuery like this:

$(location).attr('href', 'http://yourPage.com/');

Azam Alvi

Posted 2009-02-02T12:54:16.867

Reputation: 3 732

41

In JavaScript and jQuery we can use the following code to redirect the one page to another page:

window.location.href="http://google.com";
window.location.replace("page1.html");

user2496033

Posted 2009-02-02T12:54:16.867

Reputation:

40

Javascript:

window.location.href='www.your_url.com';
window.top.location.href='www.your_url.com';
window.location.replace('www.your_url.com');

Jquery:

var url='www.your_url.com';
$(location).attr('href',url);
$(location).prop('href',url);//instead of location you can use window

lalithkumar

Posted 2009-02-02T12:54:16.867

Reputation: 2 747

Is there a reason for storing the url in jQuery as a variable, but not with Vanilla? – ESR – 2017-08-10T05:00:02.547

40

ECMAScript 6 + jQuery, 85 bytes

$({jQueryCode:(url)=>location.replace(url)}).attr("jQueryCode")("http://example.com")

Please don't kill me, this is a joke. It's a joke. This is a joke.

This did "provide an answer to the question", in the sense that it asked for a solution "using jQuery" which in this case entails forcing it into the equation somehow.

Ferrybig apparently needs the joke explained (still joking, I'm sure there are limited options on the review form), so without further ado:

Other answers are using jQuery's attr() on the location or window objects unnecessarily.

This answer also abuses it, but in a more ridiculous way. Instead of using it to set the location, this uses attr() to retrieve a function that sets the location.

The function is named jQueryCode even though there's nothing jQuery about it, and calling a function somethingCode is just horrible, especially when the something is not even a language.

The "85 bytes" is a reference to Code Golf. Golfing is obviously not something you should do outside of code golf, and furthermore this answer is clearly not actually golfed.

Basically, cringe.

1j01

Posted 2009-02-02T12:54:16.867

Reputation: 1 855

37

Here is a time-delay redirection. You can set the delay time to whatever you want:

<!doctype html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Your Document Title</title>
    <script type="text/javascript">
        function delayer(delay) {
            onLoad = setTimeout('window.location.href = "http://www.google.com/"', delay);
        }
    </script>
</head>

<body>
    <script>
        delayer(8000)
    </script>
    <div>You will be redirected in 8 seconds!</div>
</body>

</html>

Stefan Gruenwald

Posted 2009-02-02T12:54:16.867

Reputation: 1 966

5

better do this: setTimeout(function() {window.location.href = "http://www.google.com/"}, delay);

– dikkini – 2014-04-04T21:33:51.833

34

There are three main ways to do this,

window.location.href='blaah.com';
window.location.assign('blaah.com');

and...

window.location.replace('blaah.com');

The last one is best, for a traditional redirect, because it will not save the page you went to before being redirected in your search history. However, if you just want to open a tab with JavaScript, you can use any of the above.1

EDIT: The window prefix is optional.

Ben

Posted 2009-02-02T12:54:16.867

Reputation: 1 391

34

I just had to update this ridiculousness with yet another newer jQuery method:

var url = 'http://www.fiftywaystoleaveyourlocation.com';
$(location).prop('href', url);

Epiphany

Posted 2009-02-02T12:54:16.867

Reputation: 1 306

32

Write the below code after the PHP, HTML or jQuery section. If in the middle of the PHP or HTML section, then use the <script> tag.

location.href = "http://google.com"

Bidyut

Posted 2009-02-02T12:54:16.867

Reputation: 396

28

jQuery code to redirect a page or URL

First Way

Here is the jQuery code for redirecting a page. Since, I have put this code on the $(document).ready() function, it will execute as soon as the page is loaded.

var url = "http://stackoverflow.com";
$(location).attr('href',url);

You can even pass a URL directly to the attr() method, instead of using a variable.

Second Way

 window.location.href="http://stackoverflow.com";

You can also code like this (both are same internally):

window.location="http://stackoverflow.com";

If you are curious about the difference between window.location and window.location.href, then you can see that the latter one is setting href property explicitly, while the former one does it implicitly. Since window.location returns an object, which by default sets its .href property.

Third Way

There is another way to redirect a page using JavaScript, the replace() method of window.location object. You can pass a new URL to the replace() method, and it will simulate an HTTP redirect. By the way, remember that window.location.replace() method doesn't put the originating page in the session history, which may affect behavior of the back button. Sometime, it's what you want, so use it carefully.

// Doesn't put originating page in history
window.location.replace("http://stackoverflow.com");

Fourth Way

like attr() method (after jQuery 1.6 introduce)

var url = "http://stackoverflow.com";
$(location).prop('href', url);

Divyesh Kanzariya

Posted 2009-02-02T12:54:16.867

Reputation: 1 886

27

In JavaScript and jQuery we use this following code to redirect the page:

window.location.href="http://google.com";
window.location.replace("page1.html");

But you can make a function in jQuery to redirect the page:

jQuery.fn.redirect=function(url)
{
    window.location.href=url;
}

And call this function:

jQuery(window).redirect("http://stackoverflow.com/")

Muhammad Waqas

Posted 2009-02-02T12:54:16.867

Reputation: 1 198

25

In jQuery, use $(location).attr('href', url):

$(document).ready(function(){
    var url = "https://www.youtube.com/watch?v=JwMKRevYa_M";
    $(location).attr('href', url); // Using this
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

In raw JavaScript, there are a number of ways to achieve that:

window.location.href="https://www.youtube.com/watch?v=JwMKRevYa_M";

- sets href property explicitly.

window.location = "http://www.GameOfThrones.com";

- does it implicitly Since window.location returns an object, which by default sets its .href property.

window.location.replace("http://www.stackoverflow.com");

- replaces the location of the current window with the new one.

self.location = "http://www.somewebsite.com";

- sets the location of the current window itself.

Here is an example of JavaScript redirecting after a certain time (3 seconds):

<script>
    setTimeout(function() {
        window.location.href = "https://www.youtube.com/";
    }, 3000);
</script>

Inconnu

Posted 2009-02-02T12:54:16.867

Reputation: 3 537

24

Using JavaScript:

Method 1:

window.location.href="http://google.com";

Method 2:

window.location.replace("http://google.com");

Using jQuery:

Method 1: $(location)

$(location).attr('href', 'http://google.com');

Method 2: Reusable Function

jQuery.fn.redirectTo = function(url){
    window.location.href = url;
}

jQuery(window).redirectTo("http://google.com");

Kalpesh Panchal

Posted 2009-02-02T12:54:16.867

Reputation: 527

23

Use the jQuery function:

$.extend({
  redirectPost: function(location, args) {
    var form = '';
    $.each(args, function(key, value) {
      form += '<input type="hidden" name="' + key + '" value="' + value + '">';
    });
    $('<form action="' + location + '" method="POST">' + form + '</form>').appendTo($(document.body)).submit();
  }
});

In your code you use it like this:

$.redirectPost("addPhotos.php", {pimreference:  $("#pimreference").val(), tag: $("#tag").val()});

stratum

Posted 2009-02-02T12:54:16.867

Reputation: 239

18

Simply in JavaScript, you can redirect to a specific page by using the following:

window.location.replace("http://www.test.com");

Or

location.replace("http://www.test.com");

Or

window.location.href = "http://www.test.com";

Using jQuery:

$(window).attr("location","http://www.test.com");

vipul sorathiya

Posted 2009-02-02T12:54:16.867

Reputation: 997

16

<script type="text/javascript">
var url = "https://yourdomain.com";

// IE8 and lower fix
if (navigator.userAgent.match(/MSIE\s(?!9.0)/))
{
    var referLink = document.createElement("a");
    referLink.href = url;
    document.body.appendChild(referLink);
    referLink.click();
}

// All other browsers
else { window.location.replace(url); }
</script>

Jaydeep Jadav

Posted 2009-02-02T12:54:16.867

Reputation: 492

15

Here is the code to redirect to some other page with a timeout of 10 seconds.

<script>
    function Redirect()
    {
        window.location="http://www.adarshkr.com";
    }

    document.write("You will be redirected to a new page in 10 seconds.");
    setTimeout('Redirect()', 10000);
</script>

You can also do it like this, on click of a button using location.assign:

<input type="button" value="Load new document" onclick="newPage()">
<script>
    function newPage() {
        window.location.assign("http://www.adarshkr.com")
    }
</script>

Adarsh Gowda K R

Posted 2009-02-02T12:54:16.867

Reputation: 806

don't use inline click events. Bad practice and is not going to be supported in future iterations of all web browsers. – Patrick W. McMahon – 2014-12-18T16:54:29.197

14

You can use it like in the following code where getGuestHouseRequestToForward is the request mapping (URL). You can also use your URL.

function savePopUp(){
    $.blockUI();
    $.ajax({
        url:"saveForwardingInformationForGuestHouse?roomType="+$("#roomType").val(),
        data: $("#popForm").serialize(),
        dataType: "json",
        error: (function() {
            alert("Server Error");
            $.unblockUI();
    }),
    success: function(map) {
        $("#layer1").hide();
        $.unblockUI();
        window.location = "getGuestHouseRequestToForward";
    }
});

This is for the same context of the application.

If you want to use only jquery specific code then following code may help:

 $(location).attr('href',"http://www.google.com");
 $jq(window).attr("location","http://www.google.com");
 $(location).prop('href',"http://www.google.com"); 

Vinay Sharma

Posted 2009-02-02T12:54:16.867

Reputation: 514

13

You can use:

window.location.replace("http://www.example.com/");

The replace() method does not save the originating page in the session history, so the user can't go back using the back button and again get redirected. NOTE: The browser back button will be deactivated in this case.

However, if you want an effect the same as clicking on a link you should go for:

window.location.href = "http://www.example.com/";

In this case, the browser back button will be active.

madhur

Posted 2009-02-02T12:54:16.867

Reputation: 616

13

You can redirect the page by using the below methods:

  1. By using a meta tag in the head - <meta http-equiv="refresh" content="0;url=http://your-page-url.com" />. Note that content="0;... is used for after how many seconds you need to redirect the page

  2. By using JavaScript: window.location.href = "http://your-page-url.com";

  3. By using jQuery: $(location).attr('href', 'http://yourPage.com/');

SantoshK

Posted 2009-02-02T12:54:16.867

Reputation: 1 134

13

<script type="text/javascript">
    if(window.location.href === "http://stackoverflow.com") {      
         window.location.replace("https://www.google.co.in/");
       }
</script>

sneha

Posted 2009-02-02T12:54:16.867

Reputation: 317

11

This is very easy to implement. You can use:

window.location.href = "http://www.example.com/";

This will remember the history of the previous page. So one can go back by clicking on the browser's back button.

Or:

window.location.replace("http://www.example.com/");

This method does not remember the history of the previous page. The back button becomes disabled in this case.

Abhishek K. Upadhyay

Posted 2009-02-02T12:54:16.867

Reputation: 676

11

Javascript is very extensive. If you want to jump to another page you have three options.

 window.location.href='otherpage.com';
 window.location.assign('otherpage.com');
 //and...

 window.location.replace('otherpage.com');

As you wants to move to other page you can use any from there if this is your requirment However all three options are limited to diffrent situations. Chose wisely according to your requirment.

if you are intrested in more knowledge about the concept. You can go through further.

window.location.href returns the href (URL) of the current page
window.location.hostname returns the domain name of the web host
window.location.pathname returns the path and filename of the current page
window.location.protocol returns the web protocol used (http: or https:)
window.location.assign loads a new document

Asif J

Posted 2009-02-02T12:54:16.867

Reputation: 845

10

I already use the function redirect() of JavaScript. It's working.

<script type="text/javascript">
    $(function () {
        //It's similar to HTTP redirect
        window.location.replace("http://www.Technomark.in");

        //It's similar to clicking on a link
        window.location.href = "Http://www.Technomark.in";
    })
</script>

user1012506

Posted 2009-02-02T12:54:16.867

Reputation: 928

10

Use:

function redirect(a) {
    location = a
}

And call it with: redirect([url]);

There's no need for the href after location, as it is implied.

cascading-style

Posted 2009-02-02T12:54:16.867

Reputation: 150

10

Single Page Application, within the same application route

window.location.pathname = '/stack';

JavaScript:

location.href = "http://stack.com";
window.location = "http://stack.com";

jQuery:

$(location).attr('href', "http://www.stack.com");
$(window).attr('location', "http://www.stack.com");

Angular 4

import { Router } from '@angular/router';
export class NavtabComponent{
    constructor(private router: Router) {
    }
    this.router.navigate(['bookings/taxi']);
}

HD..

Posted 2009-02-02T12:54:16.867

Reputation: 860

8

All way to make a redirect from the client side:

<!DOCTYPE html>
<html>
    <head>
        <title>JavaScript and jQuery example to redirect a page or URL </title>
    </head>
    <body>
        <div id="redirect">
            <h2>Redirecting to another page</h2>
        </div>

        <script src="scripts/jquery-1.6.2.min.js"></script>
        <script>
            // JavaScript code to redirect a URL
            window.location.replace("http://stackoverflow.com");
            // window.location.replace('http://code.shouttoday.com');

            // Another way to redirect page using JavaScript

            // window.location.assign('http://code.shouttoday.com');
            // window.location.href = 'http://code.shouttoday.com';
            // document.location.href = '/relativePath';

            //jQuery code to redirect a page or URL
            $(document).ready(function(){
                //var url = "http://code.shouttoday.com";
                //$(location).attr('href',url);
                // $(window).attr('location',url)
                //$(location).prop('href', url)
            });
        </script>
    </body>
</html>

Zigri2612

Posted 2009-02-02T12:54:16.867

Reputation: 1 214

8

I just add another way:

To redirect for any specific page/links of your site to another page, just add this line of code:

<script>
    if(window.location.href == 'old_url')
    {
        window.location.href="new_url";
    }

    // Another URL redirect
    if(window.location.href == 'old_url2')
    {
        window.location.href="new_url2";
    }
</script>

For a real life example,

<script>
    if(window.location.href == 'https://old-site.com')
    {
        window.location.href="https://new-site.com";
    }

    // Another URL redirect
    if(window.location.href == 'https://old-site.com/simple-post.html')
    {
        window.location.href="https://new-site.com/simple-post.html";
    }
</script>

By using this simple code, you can redirect full site or any single page.

Maniruzzaman Akash

Posted 2009-02-02T12:54:16.867

Reputation: 1 431

8

  1. location.assign():

    To assign a route path by passing a path into it.. Assign will give you a history even after the path was assigned.

    Usage Method: value should be passed into it.

    For example: location.assign("http://google.com")

    Enter image description here

  2. location.href

    Can define give a path into it... And it will redirect into a given path once it setup, and it will keep history...

    Usage Method: value should be assign into it.

    For example: location.href = "http://google.com"

  3. location.replace():

    It will help to replace a path if you don't want to keep history. It won't give you a history once you replace its path.

    Usage Method: value should be pass into it.

    For example: location.replace("http://google.com")

    Enter image description here


assign() and href are similar, and both can hold history. assign will work by passing a value and href works by assigning.

You can achieve it using JavaScript itself without using jQuery by assigning,

window.location = "http://google.com"
location.href = "http://google.com"

You can achieve similar thing using jQuery like below. It will do exactly the same like above,

$(window).attr('location', "http://www.google.com");
$(location).attr('href', "http://www.google.com");

You can easily understand the difference between both...

Here is the Location object,

Location API from chrome

Mohideen ibn Mohammed

Posted 2009-02-02T12:54:16.867

Reputation: 6 869

8

If you want to redirect to a route within the same app simply

window.location.pathname = '/examplepath'

would be the way to go.

RuNpiXelruN

Posted 2009-02-02T12:54:16.867

Reputation: 620

8

Using location.replace() will redirect you but without saving the history of the previous page. This better to use when a form is submitted. But when you want to keep your history you have to use location.href=//path

Examples:

// form with steps
document.getElementById('#next').onclick = function() {
   window.location.href='/step2' // iteration of steps;
}

// go to next step
document.getElementById("#back').onclick = function() {
   window.history.back();
}

// finish 
document.getElementById("#finish').onclick = function() {
   window.location.href = '/success';
}

// on success page
window.onload = function() {
    setTimeout(function() {
       window.location.replace('/home'); // i can't go back to success page by pressing the back button
    },3000);
}

Andrei Todorut

Posted 2009-02-02T12:54:16.867

Reputation: 1 894

6

Redirecting User using jQuery/JavaScript

By using the location object in jQuery or JavaScript we can redirect the user to another web page.

In jQuery

The code to redirect the user from one page to another is:

var url = 'http://www.example.com';
$(location).attr('href', url);

In JavaScript

The code to redirect the user from one page to another is:

var url = 'http://www.example.com';
window.location.href = url;

Or

var url = 'http://www.example.com';
window.location = url;

devst3r

Posted 2009-02-02T12:54:16.867

Reputation: 470

6

You can write the Url.Action for the Button click event in the script section as follows.

function onclick() {
        location.href = '@Url.Action("Index","Home")';
    }

wild coder

Posted 2009-02-02T12:54:16.867

Reputation: 355

6

If you prefer to use pure javascript I realized that using of document.location.href = "https://example.com" or window.location.href = "https://example.com" causes compatibility issues in Firefox. Instead try to use:

location.href = "https://example.com";
location.replace("http://example.com");

In my case has solved the problem. Good luck!

Alessandro Foolish Ciak DAnton

Posted 2009-02-02T12:54:16.867

Reputation: 129

5

This is how I use it.

   window.location.replace('yourPage.aspx');   
   // If you're on root and redirection page is also on the root

   window.location.replace(window.location.host + '/subDirectory/yourPage.aspx');

   // If you're in sub directory and redirection page is also in some other sub directory.

dnxit

Posted 2009-02-02T12:54:16.867

Reputation: 4 534

1

@Phil you ever came across sub directories in you application suppose if you're on http://www.url.com/admin/login.aspx you want to go to http://www.url.com/customer/orders.aspx window.location.host will give you http://www.url.com then you can append your sub directory and page

– dnxit – 2014-02-11T07:05:13.613

3

In my work experience, JavaScript is much better to redirect.

It depends on how you want to change the location. If you want to log your website in users history, use window.location.href='ur website';. Otherwise to do it without logging in history, use window.location.replace("your website");.

Omkaar.K

Posted 2009-02-02T12:54:16.867

Reputation: 1 167