Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a query parameter along with a redirect in JavaScript

Tags:

javascript

Right now redirection is made simply by saying

window.location = "/relative_path/";

What I want to do is to add a query parameter along with this redirection, so the destination page can look at that, and after some action was taken it could redirect further to that page.

Example for that use is a login system. When the user's token expires, he is redirected to the login page. At the time of the redirection I want to pass along the exact URL (including query parameters in the URL) to the login page, so after a successful login the user could be redirected back exactly to the point where he/she was.

I tried to pass the path as a URL parameter, but that doesn't work because of escaping issues: the redirect url uses the same characters (?, =, ...), which confuses the system, and the parameters get truncated.

So something like that, but this obviously doesn't work:

window.location = "/login?redirect=/original_location?p1=vl1&p2=v2

Any suggestion is appreciated.

like image 902
Csaba Toth Avatar asked Mar 17 '15 06:03

Csaba Toth


People also ask

How do I pass a value to a redirect URL?

Click Action > URL Redirect. Give your action an internal title (something that makes sense to you in the survey). Enter the link to the site in the URL field. Scroll to the Fields To Pass and select the question, hidden value, or URL Variables you would like to pass in the Question to Send dropdown.

How do you redirect to another page in JavaScript with get data?

To redirect to another page in JavaScript, you can use window. location. href property, window. location will also work and if you want you can use window.

How do I redirect a specific part of a page using JavaScript?

One can use the anchor tag to redirect to a particular section on the same page. You need to add ” id attribute” to the section you want to show and use the same id in href attribute with “#” in the anchor tag.


1 Answers

You can use encodeURIComponent()

The encodeURIComponent() method encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).

Example

window.location = "/login?redirect=" + encodeURIComponent("/original_location?p1=vl1&p2=v2")
like image 58
Satpal Avatar answered Oct 01 '22 07:10

Satpal