JavaScirpt Tutorial Index

JavaScript Tutorial Javascript Example Javascript comment Javascript Variable Javascript Data Types Javascript Operators Javascript If Else Javascript Switch Statement Javascript loop JavaScript Function Javascript Object JavaScript Arrays Javascript String Javascript Date Javascript Math Javascript Number Javascript Dialog Box Javascript Window Object Javascript Document Object Javascript Event Javascript Cookies Javascript getElementByID Javascript Forms Validation Javascript Email Validation Javascript Password Validation Javascript Re-Password Validation Javascript Page Redirect Javascript Print How to Print a Page Using JavaScript Textbox events in JavaScript How to find the largest number contained in a JavaScript Array?

Misc

JavaScript P5.js JavaScript Minify JavaScript redirect URL with parameters Javascript Redirect Button JavaScript Ternary Operator JavaScript radio button checked value JavaScript moment date difference Javascript input maxlength JavaScript focus on input Javascript Find Object In Array JavaScript dropdown onchange JavaScript Console log Multiple variables JavaScript Time Picker Demo JavaScript Image resize before upload Functional Programming in JavaScript JavaScript SetTimeout() JavaScript SetInterval() Callback and Callback Hell in JavaScript Array to String in JavaScript Synchronous and Asynchronous in JavaScript Compare two Arrays in JavaScript Encapsulation in JavaScript File Type Validation while Uploading Using JavaScript or jquery Convert ASCII Code to Character in JavaScript Count Character in string in JavaScript Get First Element of Array in JavaScript How to convert array to set in JavaScript How to get current date and time in JavaScript How to Remove Special Characters from a String in JavaScript Number Validation in JavaScript Remove Substring from String in JavaScript

Interview Questions

JavaScript Interview Questions JavaScript Beautifier Practice Javascript Online Object in JavaScript JavaScript Count HTML Interpreter Getters and Setters in JavaScript Throw New Error in JavaScript XOR in JavaScript Callbacks and Promises in JavaScript Atob in JavaScript Binary in JavaScript Palindrome Number in JavaScript How to Get First Character Of A String In JavaScript How to Get Image Data in JavaScript How to get URL in JavaScript JavaScript GroupBy Methods difference-between-var-let-and-const-keyword-in-java-script

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