×

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 Date

In JavaScript Date Object is data type build into the JavaScript language. Data object are created with the new Date(). JavaScript Date instance that represents a single moment in time. JavaScript...

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 Tutorial

JavaScript is a light-weight, dynamic scripting language that is mainly employed to create interactive front-end web applications. It was originally developed in 1995 by Brendan Eich at Netscape Communications Corporation...

5 minutes read.

Javascript String

String object works with series of characters. It is used to store and manipulate text. There are two ways to create string in JavaScript: String literal. Using new keyword. String literal By using double quotes...

4 minutes read.

JavaScript moment date difference

Often date differences are required on the web platforms for various reasons. They can be: To find the duration, of course, someone is pursuingTo find the age of a user from...

7 minutes read.

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 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 comment

Introduction In programming languages, comments are a method to include meaningful annotations within the code that the compiler or interpreter will ignore at run time. That is to say, though comments...

7 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 Document Object

Document object represents the whole HTML documents. When HTML document is loaded in browser it becomes the document object. It is the root elements that represent the HTML documents. With the help of...

2 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 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 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 getElementByID

The document.getElementById() method returns the element of specified id. In below example we receive input field by using document.getElementById() method, here document.getElementById() receive input value on the basis of input field...

1 minute read.

Synchronous and Asynchronous in JavaScript

JavaScript is a powerful and versatile language that is used all over the web, from small websites to large applications. It is essential for developers to understand the differences between...

9 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 Forms Validation

Form validation works at server, after client had entered all the necessary details and then pressed submit button. JavaScript provides the facility to validate the form on the client side...

9 minutes 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.

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 Event

Events are things that happen, usually user action, that are associated with an object. All object have properties and methods. Some objects also have events. The event handler is a command that is...

1 minute read.