JS window.location not working - javascript

My window.location does not redirect the page to the required location. The same code with window.open works. The else statement also executes when the user name and password are incorrect. When the correct username and password is entered, it just refreshes the same page.
<div class="login" style="position:relative;top:200px;">
<form name="login" method="post">
<p align="middle">Please login to continue </p><p align="middle"><input type="text" name="login" placeholder="Username"></p>
<p align="middle"><input type="password" name="pwd" placeholder="Password"></p>
<p class="submit" align="middle"><input type="submit" onclick ="return check(this.form)" value="Login" name="commit"></p>
</form>
<script language="javascript">
function check(form) {
if(form.login.value == "admin" && form.pwd.value == "sysadmin") {
window.location('alumni.html');
}
else {
alert("Ten thousand thundering typhoons! What is the blasted password?");
}
}
</script>
<!--<script type='text/javascript' src='alumna.json'></script> -->
</div>

You can also try with
window.location = 'http://www.yoururl.com/alumni.html';
or directly
window.location = 'alumni.html';
There is a good question about redirect in javascript here: How do I redirect with Javascript?
[EDIT #1]
Although I think that is not the main problem. I believe you can not validate the way you are doing it. In the form there is an attribute called action as explained in http://www.w3schools.com/tags/att_form_action.asp
Then in the page you load, you validate the parameters and decide if its right or not, where you redirect to one page if its right, or to another if it's wrong.
Or you can also load the page and if validation is right, stay in the page and if it's wrong redirect to the login page.
That's one way to do it, probably there is another one better.
[EDIT #2]
What I would personally do is to process the form in a PHP page, it's much easier and simpler. Could be like:
in the HTML:
<div class="login" style="position:relative;top:200px;">
<form name="login" action="myPhpPage.php" method="post">
<p align="middle">Please login to continue </p>
<p align="middle"><input type="text" name="login" placeholder="Username"></p>
<p align="middle"><input type="password" name="pwd" placeholder="Password"></p>
<p class="submit" align="middle">
<input type="submit" onclick ="" value="Login" name="commit"></p>
</form>
<!--<script type='text/javascript' src='alumna.json'></script> -->
</div>
In the PHP page:
$name = $_POST['login']; // it's $_post because you are sending the form with method = post
$pass = $_POST['pwd'];
if($name == "admin" && $pass == "sysadmin"){
//go to one page or stay here
} else{
// redirect to another page
}

window.location is a read only property:
The Window.location read-only property returns a Location object with information about the current location of the document.
MDN on window.location
try this: window.location.replace("http://stackoverflow.com");

Here's a working code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title> Login Redirection Test</title>
<script>
function validateForm() {
var un = document.forms["login"]["user"].value;
var pw = document.forms["login"]["pwd"].value;
if (un == "admin" && pw=="sysadmin") {
window.location.assign="https://stackoverflow.com";
return false;
}else {
alert("Ten thousand thundering typhoons! What is the blasted password?");
}
}
</script>
</head>
<body>
<div class="login" style="position:relative;top:200px;">
<form name="login" onsubmit="return validateForm()" method="post">
<p align="middle">Please login to continue </p><p align="middle"><input type="text" name="user" placeholder="Username"></p>
<p align="middle"><input type="password" name="pwd" placeholder="Password"></p>
<p class="submit" align="middle"><input type="submit" onclick ="return check(this.form)" value="Login" name="commit"></p>
</form>
<!--<script type='text/javascript' src='alumna.json'></script> -->
</div>
</body>
</html>

Window.location is not a function, it is a property that is just read. However,
window.location.assign
might work better.

Related

I can't get Tag content with a Script/Function

i'm with a ridiculous problem (i think). I just can't get a tag content using a Script/Function/document.getElementById. The alert tha i'm using to see the content of variable (wM) is always blank. I looked a lot of examples in the Web and all of them is similar, sometimes just like my code. See below:
<!DOCTYPE html>
<html lang ="pt-br">
<head>
<title> loginServlet2 </title>
<meta http-equiv = ”Content-Type” content=”text/html; charset=UTF-8”>
<link rel="stylesheet" type="text/css" href="c:/java/html/css/estilo.css"/>
<script type="text/javascript">
function oMsg()
{
var wM = document.getElementById("wMsgB").textContent;
// var wM = document.querySelector("span").textContent;
alert("wM = "+ wM);
if (wM == "Teste OK!")
{
// document.getElementById("wMsgA").innerHTML = "Test is OK";
document.getElementById("wMsgA").textContent = "Test is OK";
}
else
{
alert("Test is not OK. Before set new msg");
document.getElementById("wMsgA").textContent = "Test is not OK";
}
}
</script>
</head>
<body>
<h2> Login Page2 </h2>
<p>Please enter your username and password</p>
<form method="GET" action="loginServlet2">
<p id="test2"> Username <input type="text" name="userName" size="50"> </p>
<p> Password <input type="password" name="password" size="20"> </p>
<p> <input type="submit" value="Submit" name="B1" onclick="oMsg()"> </p>
</form>
<h3> MsgB : <span id="wMsgB"<%=request.getAttribute("wMsg")%></span></h3>
<p> MsgA : <span id="wMsgA"> </span> </p>
</body>
</html>
Could anyone help me, please? Thanks.
You are trying to get the value of a p element, but p elements don't have a value property. Only form fields do. Non-form fields that contain text between their opening and closing tags have .textContent and .innerHTML properties you can use to get/set their contents.
If you want to give the user a place to type in some data, you need to create some input form fields and then you have to wait until they've done that before attempting to get the values.
Next, you have smart quotes “” instead of straight quotes "" which can cause encoding problems. Make sure you write your code in an editor that doesn't apply any formatting to the code. There are plenty of great free web editors out there.
You also have a reference to a .css file using a full local path, which isn't going to work when you deploy this code later. You should be using relative paths to reference files that are part of your system.
Finally, you are using some old HTML syntax in your meta, link and script tags, so take note of the modern versions of those in the snippet below.
<head>
<title>loginServlet2</title>
<meta charset=UTF-8”>
<link rel="stylesheet" href="c:/java/html/css/estilo.css"/>
<script>
function oMsg() {
var wM = document.getElementById("wMsg").textContent;
alert("wM = " + wM);
if (wM == "Test OK!") {
document.getElementById("wMsgA").textContent = "Test is OK";
} else {
alert("Test is not OK. Before set new msg");
document.getElementById("wMsgA").textContent = "Test is not OK";
}
}
</script>
</head>
<body>
<h2> Login Page2 </h2>
<p>Please enter your username and password</p>
<form method="GET" action="loginServlet2">
<p id="test2"> Username <input type="text" name="userName" size="50"> </p>
<p> Password <input type="password" name="password" size="20"> </p>
<p> <input type="submit" value="Submit" name="B1" onclick="oMsg()"> </p>
</form>
<h2>MsgB : <span id="wMsg"><%=request.getAttribute("wMsg")%></span> </h2>
<p>MsgA : <span id="wMsgA"> </span> </p>

Validating and linking to another page

I have created a login page.In whicn iam unable to link it with the next page after clicking submit button.I want to validate and redirect to the next page.ie home.php.Kindly help me find out what am i missing.
signin.php
<!DOCTYPE html>
<html>
<head>
<script>
function val()
{
var a=document.signin.user.value;
var b=document.signin.password.value;
if ( a == "admin" && b == "rec"){
alert ("Login success");
window.location = "home.php";
return false;
}
else{
alert("login failed")
}
}
</script>
<meta charset="UTF-8">
<title>LIBRARY </title>
</head>
<body>
<div class="body"></div>
<div class="grad"></div>
<div class="header">
<div>REC<span>LIBRARY</span></div>
</div>
<br>
<br>
<br>
<div class="login">
<form name="signin" method="post" onsubmit="val();">
<input type="text" placeholder="username" name="user"><br>
<input type="password" placeholder="password" name="password"><br>
<input type="submit" id="mybutton" value="login"></form>
</div>
</body>
</html>
The problem is the onsubmit event is not having false returned to it, so it posts the form normally, after your JavaScript has finished. Even in the case of successful login and the redirect is executed, the form will still submit and it will override the redirect.
Firstly, Move your return false; to the end of the function, so that it always executes.
Secondly, change your onsubmit="val();" to onsubmit="return val();". This means the onsubmit event will always be returned false and will not try to post the form.
Side note: this is by no means a secure system. Any visitor can simply observe the HTML source to find the password, or just navigate directly to home.php. For a secure system, you will need to do the authentication on the server side (in the PHP).
You could use preventDefault() Event method without using onsubmit=val() like below.
document.getElementById("signin").addEventListener("submit", function(e){
e.preventDefault()
// actual code to validate
});
or
can try some dirty work on server side directly to hide the validation part
<?php
ob_start();
session_start();
loginForm();
$userinfo = array(
'admin'=>'0b2c082c00e002a2f571cbe340644239'
);
if(isset($_POST['username'])){
if($userinfo[$_POST['username']] == md5($_POST['password'])){
$_SESSION['username'] = $_POST['username'];
header('Location: home.php');
exit();
}else{
?>
<script type="text/javascript">
alert("Oops.... User name or Pasword is worng, Please try again");
</script>
<?php
}
}
function loginForm()
{
?>
<form name="login" action="" method="post">
Username: <input type="text" name="username"> <br><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="login">
</form>
<?php
}
?>

Javascript/PHP auto submit keeps submitting form

This code:
<?php
if(isset($_GET['submit']))
{
?>
<head>
<script type="text/javascript">
document.getElementById('up').submit(); // SUBMIT FORM
</script>
</head>
<?php
}
?>
form:
<form name="up" id="up" action="" method="post">
<textarea name="text" rows="40" cols="100"></textarea>
<input type="submit" name="ingameban" value="Save in-game banlist (Upload to server and make new bans take effect)" style="height: 64px; width: 550px;" />
</form>
Keeps looping all the time, the same result as smashing the reload button.
It has to submit the form when the url states ?submit=submit
What to do to fix this?
Thanks
Your approach is right, but the problem is that submit=submit in the URL is copied to the new URL used to submit the form. Because in your form you have:
<form name="up" id="up" action="" method="post">
Since action is empty, the exact same URL is used, so submit=submit stays in the URL. Instead, provide the proper URL in action. Then submit=submit won't be copied to the new URL:
<form name="up" id="up" action="/my-url" method="post">
How about setting an input hidden field, which you mark as true when you submit.
Check this field before submitting again.
Try this:
<?php
if(isset($_GET['submit']))
{
if(isset($_GET['submitted']) && $_GET['submitted'] == 'false') {
?>
<head>
<script type="text/javascript">
document.getElementById('submitted').value = 'true';
document.getElementById('up').submit(); // SUBMIT FORM
</script>
</head>
}
<?php
}
?>
<body>
<form method="get" id="up">
<input type="hidden" id="submitted" name="submitted" value="false" />
...
</form>

Redirection error from one page to another in html and javascript?

Hi guys i have a following code in which i am trying to redirect to another ,i am using javascript html to achieve this,and i am new to html, javascript and php. It is showing test.phpbut as i click on button it does not redirect to logout_success.php.
<!DOCTYPE HTML>
<html>
<head>
<title>Sign-In</title> <link rel="stylesheet" type="text/css" href="style-sign.css">
</head>
<body id="body-color">
<div id="Sign-In">
<fieldset style="width:30%">
<legend>LOG-IN HERE</legend>
<form method="POST" action="connectivity.php">
User
<br>
<input type="text" name="user" size="40">
<br>
Password
<br>
<input type="password" name="pass" size="40"><br>
<input id="button" type="submit" name="submit" value="Log-In" onclick="document.location.href='http://localhost:8080/PortalWork/logout_success.php'">
</form>
</fieldset>
</div>
</body>
</html>
There are two ways.
(1) Submit form with AJAX, and redirect with window.location.href
$("#form1").submit(function(e){
e.preventDefault();
$.ajax({
url:'connectivity.php',
method:'POST',
success:function(rs){
if( rs == "success" )
window.location.href("logout_success.php");
},
error:function(){
alert("Error");
}
});
return false;
});
http://jsfiddle.net/hxm49uk2/
(2) Submit to server, and redirect with header("Location:page.php");
connectivity.php
header("Location:logout_success.php");
You can do it in JS like this:
<button name="button" onclick="window.location.href='http://www.google.com'">Go</button>
Instead of http://www.google.com use your desired url.
Just include the following code in connectivity.php
header("Location:logout_success.php"); // give the correct path of logout_success.php
And take off onclick from form submit button
<input id="button" type="submit" name="submit" value="Log-In">

Block specific keyword search from form

my search form on my page is
<form id="headbar-search" action="search.php" method="GET" x-webkit-speech="x-webkit-speech">
<input type="text" name="search" id="jsid-search-input" value="<?php echo$_GET['search']; ?>" class="ui-autocomplete-input search search_input" placeholder="Search…" tabindex="1"/>
<div class="ui-widget"></div>
</form>
i dont want users to be able to search certain words....
if they search "f***" i want it to redirect to the home page or a simple javascript notification that says not allowed.... thanks!
Either trap for bad words in your php script, or put your php request behind some javascript and trap there. example....
html...
<html>
<head>
<link rel="stylesheet" href="style.css"></link>
<script src="functions.js"></script>
</head>
<body>
<form id="headbar-search">
<input type="text" id="search-box"/>
<input type="submit" onclick="search();"></input>
</form>
</body>
</html>
js...
var badWords = ["gosh","darn"];
function search() {
var searchStr = document.getElementById("search-box").value;
var badWordHit = false;
for (key in badWords) {
if (badWords[key] == searchStr) {
badWordHit = true;
}
}
if (badWordHit) {
alert("Oh no you didn't!");
} else {
// ajax request here
}
}

Categories

Resources