×

JavaScript redirect URL with parameters

Data can be often passed between web pages as information in URL parameters or query strings. A URL (Uniform Resource Locator) can have a single parameter or multiple parameters.
Parameters can be passed when redirecting to another page using a JavaScript code; we can pass parameters (single or multiple) to the URL.

How are redirect URLs created using JavaScript?

There are three major ways to redirect to another webpage using JavaScript.

They are:

  • Using location.replace()
  • Using location.href()
  • Using location.assign()

How are multiple parameters passed in the URL?

To insert multiple parameters in the URL, they should be defined with values using the “?” (Question mark), "#"(Hashtag) and “&” (ampersand) symbols before redirecting.

  • What does the “?” mean?

The question mark “?” in the URLs acts as a separator. It indicates the end of the URL resource path and the start of the query parameters.

The query parameters are appended in the URL itself, and hence to differentiate the URL path and parameters "?" symbol is used.

  • What does the “&” mean?

When these symbols are used as part of a URL, the “?” and “&” represent key-value pairs that form the Query String, which is a set of information sent to the server.

These key-value pairs are separated from the main URL by "?", but the "&" symbol helps to add any additional key-value pairs that need to be prefaced. Basically, this symbol helps to add multiple parameters in the URL.

  • What does the “#” mean?

The hashtag symbol "#” usually separates the anchor from the page itself. The anchor, when present, indicates that when the page is loaded or refreshed, it should scroll to a particular section. The “#” symbol and everything afterwards is not sent to the server but remains on the client-side.

The values used in the URL can be of two types:

  • They can be hardcoded

Syntax:

<script>
function functionname{
        const url = "url?id1=value1&id2=value2";
        window.location.href = url;
    };
</script>

Here, the “id1” and “id2” are the parameter IDs, and “value1” and “value2” demonstrate the hardcoded values taken by the parameters.

“url” is any address to the website or the document we want to redirect to.

Example:

Here, we are passing a URL to google search “javatpoint” and “cpp”, hence the URL takes two parameters,

<!DOCTYPE >
<html >
<head>
    <title>Javascript redirect URL</title>
    
</head>
<body>
    <h3>After taking multiple parameters though hardcoding, we have the following information that you need:</h3><br /><br />  
    <input type="button" value="Search" onclick="Submit()" />
    <script type="text/javascript">
      
    function Submit(){
        const url = "https://www.google.com/search?q=javatpoint&q=cpp";
        window.location.href = url;
    };


    </script>
</body>
</html>

Output:

JavaScript Redirect URL With Parameters

After clicking on the submit button, the page is redirected,

JavaScript Redirect URL With Parameters
  • The input is given by the user

Here, the URL parameters can be passed through user inputs. These can be taken using <input> tag (through text boxes), drop-down lists etc.

Syntax:

<script type="text/javascript">
        function demo() {
            var val1 = document.getElementById("id1").value;
            var val2 = document.getElementById("id2").value;
            var url = "url?id1=" + encodeURIComponent(val1) + "&id2=" + encodeURIComponent(val2);
            window.location.href = url;
        };
</script>

Example:

Here, two HTML files are created, one landing page(indexpage.html) and one redirect page(redirectpage.html)

indexpage.html

<!DOCTYPE >
<html >
<head>
    <title>Javascript redirect URL</title>
    
</head>
<body>
    Enter your name here:
    <input type="text" id="textName" name="Name" value="JavaTpoint" /><br />
    <br/>
    Choose your prefered language:
    <select id="ddlang" name="language">
        <option value="C++">C++</option>
        <option value="Java">Java</option>
        <option value="Python">Python</option>
        <option value="Javascript">Javascript</option>
        <option value="Ruby">Ruby</option>
    </select>
    <br>
    <br>
    <input type="button" value="Submit" onclick="Submit()" />
    <script type="text/javascript">
        function Submit() {
            var name = document.getElementById("textName").value;
            var lang = document.getElementById("ddlang").value;
            var url = "redirectpage.htm?name=" + encodeURIComponent(name) + "&language=" + encodeURIComponent(lang);
            window.location.href = url;
        };
    </script>
</body>
</html>

redirectpage.html

<!DOCTYPE >
<html>
<head>
    <title>Javascript redirect URL</title>
   
</head>
<body>
    <span id="lblredirect"></span>
    <script type="text/javascript">
        var queryString = new Array();
        window.onload = function () {
            if (queryString.length == 0) {
                if (window.location.search.split('?').length > 1) {
                    var params = window.location.search.split('?')[1].split('&');
                    for (var i = 0; i < params.length; i++) {
                        var key = params[i].split('=')[0];
                        var value = decodeURIComponent(params[i].split('=')[1]);
                        queryString[key] = value;
                    }
                }
            }
            if (queryString["name"] != null && queryString["language"] != null) {
                var val = "<h3>After taking multiple parameters from the previous page, we have the following information that you need:</h3><br /><br />";
                val += "<b>Name:</b> " + queryString["name"] + "<br> <b>Language:</b> " + queryString["language"];
                document.getElementById("lblredirect").innerHTML = val;
            }
        };
    </script>
</body>
</html>

Output:

Initially, the landing page looks like this,

JavaScript Redirect URL With Parameters

After clicking on the submit button, the page is redirected,

JavaScript Redirect URL With Parameters

Related Topics

JavaScript Console log Multiple variables

What does console.log() do in JavaScript? The console.log() is a function in JavaScript language. It is used to: Print any message in the console which is visible to the userPrint the values...

3 minutes read.

Javascript Variable

Variables are used to store values (name="Ram") or expressions (Sum=x+y). Before using of variable first we need to declare it. We use keyword var to declare a variable like this: var name; There are two types of variables: Local Variable ...

1 minute read.

Callback and Callback Hell in JavaScript

The widely used client-side programming language JavaScript is simple, light, and interpretive. JavaScript is used by the majority of client-side web applications. It is also possible to use JavaScript on...

3 minutes read.

JavaScript Function

An important part of JavaScript is the ability to create new functions within <script>.....</script> tag. To declare a function in JavaScript using function keyword. We call JavaScript function multiple times to reuse the...

3 minutes read.

JavaScript redirect URL with parameters

Data can be often passed between web pages as information in URL parameters or query strings. A URL (Uniform Resource Locator) can have a single parameter or multiple parameters.Parameters can...

4 minutes read.

Javascript Operators

The concept of operators is the basis of nearly all programming languages used in today's computing systems. Operators facilitate the execution of certain functions. For instance, the (+) symbol is...

8 minutes read.

JavaScript setInterval()

On the Window and Worker interfaces, the setInterval() method calls a function or executes a snippet with a specified time delay between each call. This function provides an interval ID that...

4 minutes read.

Array to String in JavaScript

As a web developer, you often have to deal with multiple data types in a single application. How to convert an array to a string in JavaScript is essential for...

19 minutes read.

JavaScript radio button checked value

What are radio buttons? A radio button is defined as an icon that is used to take input from the user. The user can choose only one option(value) from the group...

5 minutes read.

Design a BMI calculator using JavaScript

BMI calculator BMI stands for Body Mass Indicator. It is a numeric value which is calculated based on the height and weight of a person. It represents the fatness of the...

4 minutes read.

Javascript input maxlength

Various attributes often accompany the input tag in HTML to change the properties of the input field. Maxlength() is one such attribute. The maxLength attribute defines the maximum number of characters...

2 minutes read.

JavaScript dropdown onchange

What is onchange event? It is an event in JavaScript used to make the web pages dynamic. The onchange event gets triggered whenever the value of an event changes. It usually...

3 minutes read.

Javascript Email Validation

We can validate the email with the help of JavaScript. Here we check the condition related to any email id, like email it must have "@" and "." sign and...

2 minutes read.

Javascript Object

An object is an entity having state and behavior. JavaScript is an object oriented scripting language. JavaScript is template based not class based but we can create object directly. Syntax to...

2 minutes read.

Javascript Math

Math is build-in object that has properties and methods for mathematical constants and functions. It allows you to perform mathematical tasks on numbers. Syntax varpi_val = Math.PI; varsin_val = Math.sin(30); Examples Math.pow() Math.pow(x,y) returns the value of x to the power...

2 minutes read.

Javascript Find Object In Array

What is find() method? It returns the value of the first element in the given array that fulfils the given testing function. However, if no values from the array are able...

3 minutes read.

Functional Programming in JavaScript

Most developers work with object-oriented programming while developing their applications, but sometimes they need to change their approach to solve some specific tasks. Although mostly we tend to go for...

6 minutes read.

Javascript Switch Statement

Introduction Conditional statements are simple building blocks in programming languages and are utilized fairly frequently. This portion of Developing Conditional Statements in JavaScript talks about how to utilize the if, else,...

5 minutes read.

Javascript Cookies

Cookie is a piece of data which is sent from a website and stored locally by the user's browser. Cookie is needed because HTTP is stateless protocol. Today most of...

1 minute read.

Javascript Page Redirect

The window.location object can be used to get the current page address (URL) and to redirect browser to new page. In some websites when we visit, we face a situation where we...

3 minutes read.