How to go from one page to another page using javascript?
Asked Answered
A

8

99

From an admin page if the user is valid then the browser should go to another page.

When a user enters his user name and password, then clicks the OK button then another page is displayed and the login page is automatically closed.

How can I do this with JavaScript?

Abbreviation answered 13/12, 2010 at 6:0 Comment(1)
While its not clear exactly what you want, using javascript to handle login and redirection is not a great idea, as a savvy user can easily bypass restricts like this.Machmeter
Y
172

To simply redirect a browser using javascript:

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

To redirect AND submit a form (i.e. login details), requires no javascript:

<form action="/new_url" method="POST">
   <input name="username">
   <input type="password" name="password">
   <button type="submit">Submit</button>
</form>
Yawmeter answered 13/12, 2010 at 6:3 Comment(4)
As an extra note, at least Safari handles this: you don't need to specify a domain for the scripting method. So if your code was already at http://example.com, then simply window.location.href = 'new_url'; would work. This is particularly useful if your code will be used on multiple domains but you always want the user to be redirected to the same subpath within the domain they're already on.Requital
Is it possible for the next page to receive the information from the form POST?Bloch
@Requital Do all browsers accept that? I mean, no need to specify protocol and host?Chops
omg thank u actually i had never used javascript methods for routing because i only worked with react router or next js in the past and i was using window.location.replace all this time and that does not register in the history! I have been trying to solve this issue for so long!! window.location.href is the one!Areopagite
M
15

Try this,

window.location.href="sample.html";

Here sample.html is a next page. It will go to the next page.

Maloney answered 27/5, 2015 at 12:2 Comment(2)
Do all browsers accept that? I mean, no need to specify protocol and host?Chops
@JoãoPimentelFerreira as my knowledge goes, yes. as long as the file is in the same directoryNicolettenicoli
F
11

You cannot sanely depend on client side JavaScript to determine if user credentials are correct. The browser (and all code that executes that) is under the control of the user, not you, so it is not trustworthy.

The username and password need to be entered using a form. The OK button will be a submit button. The action attribute must point to a URL which will be handled by a program that checks the credentials.

This program could be written in JavaScript, but how you go about that would depend on which server side JavaScript engine you were using. Note that SSJS is not a mainstream technology so if you really want to use it, you would have to use specialised hosting or admin your own server.

(Half a decade later and SSJS is much more common thanks to Node.js, it is still fairly specialised though).

If you want to redirect afterwards, then the program needs to emit an HTTP Location header.

Note that you need to check the credentials are OK (usually by storing a token, which isn't the actual password, in a cookie) before outputting any private page. Otherwise anyone could get to the private pages by knowing the URL (and thus bypassing the login system).

Foredo answered 13/12, 2010 at 6:39 Comment(0)
M
7

Verifying that a user is an admin in javascript leads to trouble because javascript code is visible to anyone. The server is the one who should tell the difference between an admin and a regular user AFTER the login process and then generate the new page accordingly.

Maybe that's not what you are trying to do so to answer your question:

window.location.href="<the page you are going to>";
Mendelevium answered 13/12, 2010 at 6:10 Comment(0)
F
6

There are a few more ways to redirect:

  • location.replace("http://example.com");
  • location.href = "http://example.com"
  • window.location = "http://example.com"
  • window.location.href = "http://example.com"
Fonteyn answered 4/9, 2021 at 10:40 Comment(0)
A
4

The correct solution that i get is

<html>
      <head>
        <script type="text/javascript" language="JavaScript">
                  function clickedButton()
            {

                window.location = 'new url'

            }
             </script>
      </head>

      <form name="login_form" method="post">
            ..................
            <input type="button" value="Login" onClick="clickedButton()"/>
      </form>
 </html>

Here the new url is given inside the single quote.

Abbreviation answered 14/12, 2010 at 4:31 Comment(0)
H
1

Easier method is window.location.href = "http://example.com/new_url";

But what if you want to check if username and password whether empty or not using JavaScript and send it to the php to check whether user in the database. You can do this easily following this code.

html form -

<form name="myForm" onsubmit="return validateForm()" method="POST" action="login.php" >         
    <input type="text" name="username" id="username" />
    <input type="password" name="password" id="password" />
    <input type="submit" name="submitBt"value="LogIn" />
</form>

javascript validation-

function validateForm(){
    var uname = document.forms["myForm"]["username"].value;
    var pass = document.forms["myForm"]["password"].value;

    if((!isEmpty(uname, "Log In")) && (!isEmpty(pass, "Password"))){

        return true;
    }else{
        return false;
    }
}

function isEmpty(elemValue, field){
    if((elemValue == "") || (elemValue == null)){
        alert("you can not have "+field+" field empty");
        return true;
    }else{
        return false;
    }
}

check if user in the database using php

<?php
    $con = mysqli_connect("localhost","root","1234","users");

    if(mysqli_connect_errno()){
        echo "Couldn't connect ".mysqli_connect_error();
    }else{
        //echo "connection successful <br />";
    }

    $uname_tb = $_POST['username'];
    $pass_tb = $_POST['password'];

    $query ="SELECT * FROM user";
    $result = mysqli_query($con,$query);

    while($row = mysqli_fetch_array($result)){
        if(($row['username'] == $uname_tb) && ($row['password'] == $pass_tb)){
            echo "Login Successful";
            header('Location: dashbord.php');
            exit();
        }else{
            echo "You are not in our database".mysqli_connect_error();
        }
    }
    mysqli_close($con);
?>
Heymann answered 3/9, 2016 at 7:18 Comment(0)
D
1

For MVC developers, to redirect a browser using javascript:

window.location.href = "@Url.Action("Action", "Controller")";
Directorial answered 5/1, 2018 at 8:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.