I am new to JavaScript and am making a restaurant app which consists of a registration form. I want to check if the username already exists and if it does exist it should throw an alert to the user on button click.
JavaScript code:
<script type="text/javascript">
var db;
var shortname="R_loginDB";
var version = "1.0";
var displayName = "R_loginDB";
var maxSize = 90000;
function onBodyLoad() {
db = openDatabase(shortname,version,displayName,maxSize);
db.transaction(function(tx){
tx.executeSql('CREATE TABLE IF NOT EXISTS R(UserName TEXT NOT NULL PRIMARY KEY,Password TEXT NOT NULL,ConPassword TEXT NOT NULL)');
});
}
function ListDBValues() {
if (!window.openDatabase) {
alert('Databases are not supported in this browser.');
return;
}
$('#output').html('');
db.transaction(function(transaction) {
transaction.executeSql('SELECT * FROM R;', [], function(transaction, result) {
if (result != null && result.rows != null) {
for (var i = 0; i < result.rows.length; i++) {
var row = result.rows.item(i);
$('#output').append('<br>' + ' ' + row.UserName+ ' ' + row.Password + ' '+ row.ConPassword);
}
}
});
});
return;
}
ListDBValues();
function AddValues() {
var flag = false;
if ($("#pass").val() != $("#conpass").val()) {
alert("Passwords do not match.");
window.location.href = "r_register.html";
} else if (flag == false) {
try {
db.transaction(function(transaction) {
transaction.executeSql('INSERT INTO R(UserName, Password, ConPassword) VALUES (?,?,?)',[$('#uname').val(),$('#pass').val(),$('#conpass').val()]);
});
flag = true;
window.location.href = "login.html";
} catch(err) {
alert("Username " + $("#uname").val() + " is already taken!! Please chose another one");
window.location.href = "r_register.html";
}
}
}
AddValues();
</script>
HTML code:
<body onload="onBodyLoad()">
<div id="main">
<img id="bg" src="file:///android_asset/www/images/bigtable_1_blur.jpg"/>
<input id="uname" type="text" placeholder=" Username"></input>
<input id="pass" type="password" placeholder=" Password"></input>
<input id="conpass" type="password" placeholder=" Confirm Password"></input>
<p id="login"><b>Already have an account?<i><u>Login</u></i></b></p>
<!-- <a href="second.html"> -->
<input id="btn" type="button" value="Register" onclick="AddValues()"></input><br/>
<!-- </a> -->
<input id="btn2" type="button" value="show" onclick="ListDBValues()"/></input>
<span id="output"></span>
</div>
</body>
WebSQL API is depricated. It is unlikely to ever be supported on platforms that don't currently support it, and it may be removed from platforms that do.
Try using localStorage instead. Check out more at Cordova storage documentation
Related
here's my login page code :
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="C:\Users\Si Mohamed\Desktop\projects\game shop\jv.js">
</script>
<title>E-keys Store</title>
</head>
<script>
function verify() {
var usrname = document.getElementById("usrname").values;
var pass = document.getElementById("pass").values;
if (usrname2 == usrname && pass2 == pass) {
alert("logged in successfully");
}else {
alert("account doesnt exist");
}
}
</script>
<body>
<form class="sign" action="index.html" method="post">
<div class="sign_in">
<p class="title">SIGN IN</p>
<p class="mailtitle">Email or Username <br><input class="inp1" type="text" name="Username"
id="usrname2" value=""></p>
<p class="passtitle">Password<br><input type="password" name="Password" id="pass2"
class="inp2"></p>
<input type="checkbox" class="check1">
<div class="txt1">Remember</div>
<div class="txt2">Me</div>
<img src="signinbtn.svg" class="signinbtn" onclick="verify();" >
<a href="http://127.0.0.1:3000/Sign%20Up/index2.html" class="link1"><p>You don't have an
account? Sign up </p></a>
<p>Forgot your password?</p>
</div>
</form>
<aside class="bg">
<img src="bgblue.svg">
</aside>
</body>
</html>
and here's my code for the js linked to both login and sign up page :
var mydb = openDatabase("accounts", "0.1", "Testing Database", 1024 * 1024);
if (window.openDatabase) {
//create the table using SQL for the database using a transaction
mydb.transaction(function(t) {
t.executeSql("CREATE TABLE IF NOT EXISTS mydb (id INTEGER PRIMARY KEY, mailusr VARCHAR(50),
usrname VARCHAR(50), pass VARCHAR(100))");
});
} else {
alert("WebSQL is not supported by your browser!");
}
//function to output the list of cars in the database
function updateDrafts(transaction, results) {
//initialise the listitems variable
var listitems = "";
//get the list holder ul
var listholder = document.getElementById("drafts");
//clear the list of drafts ul
listholder.innerHTML = "";
var i;
//Iterate through the results
for (i = 0; i < results.rows.length; i++) {
//Get the current row from database
var row = results.rows.item(i);
listholder.innerHTML += "<li>" + row.mailusr + " - " + row.usrname + " - " + row.pass + "(<a
href='javascript:void(0);' onclick='deleteDraft(" + row.id + ");'>Delete this account</a>)";
}
}
//function to get the list of accounts from the database
function outputDrafts() {
//check to ensure the mydb object has been created
if (mydb) {
mydb.transaction(function(t) {
t.executeSql("SELECT * FROM mydb", [], updateDrafts);
});
} else {
alert("db not found, your browser does not support web sql!");
}
}
//function to add account
function addDraft() {
//check to ensure the mydb object has been created
if (mydb) {
//get the values of user and pass text inputs
var mailusr = document.getElementById("mailusr").value;
var usrname = document.getElementById("usrname").value;
var pass = document.getElementById("pass").value;
var pass1 = document.getElementById("pass1").value;
//Test to ensure that the user has filled all the form
if (mailusr !== "" && usrname !== "" && pass !== "" && pass == pass1) {
//Insert the user entered details into database
mydb.transaction(function(t) {
t.executeSql("INSERT INTO mydb (mailusr, usrname, pass) VALUES (?, ?, ?)", [mailusr, usrname,
pass]);
outputDrafts();
});
} else if (mailusr !== "" && usrname !== "" && pass !== "" && pass !== pass1) {
alert("Your password does not match with your confirmation");
}
else{
alert("You need to fill all fields");
}
}}
var link = document.getElementById("adduser");
link.onclick = function () { alert(1)
addDraft();
};
db.transaction(function (tx) {
tx.executeSql('SELECT * FROM LOGS', [], function (tx, results) {
var len = results.rows.length, i;
msg = "<p>Found rows: " + len + "</p>";
document.querySelector('#status').innerHTML += msg;
for (i = 0; i < len; i++) {
alert(results.rows.item(i).log );
}
}, null);
});
i can't somehow extract value by id in login page it said index.html:12 Uncaught TypeError: Cannot read property 'values' of null
at verify (index.html:12)
!
i need to manage somehow to get the database details like username and password to verify if the account of the user or not in the database created in sign up page
thanks in advance. Im a beginner in javascript and websql :D .
There are a few issues in your code:
Your input fields have id="usrname2" and id="pass2" but your JavaScript calls forgetElementById("usrname") and getElementById("pass") These elements simply don't exist. Change the Id of your fields and it will return values
You call openDatabase before you actually check if it is available, you might want to swap the lines
never ever ever, even for testing store passwords in clear. Use hash and salt to keep them secure. Make it a habit.
Good luck
I am using WebStorage to make a simple login system with username/password. (I don't know if this is the best way.)
It is working, but the problem is, it only works with one username and password. How do I make it so that it can store multiple usernames/passwords? Or perhaps I should be using a different system to do this?
Code:
<html>
<head>
</head>
<body>
<input type="text" placeholder="input username here" id="textbox">
<input type="text" placeholder="input password here" id="textbox2">
<input type="button" value="sign up" onclick="signup()">
<br>
<input type="text" placeholder="input username here" id="textbox3">
<input type="text" placeholder="input password here" id="textbox4">
<input type="button" value="login" onclick="login()">
<p id="result"></p>
<br>
<br>
<div id="settings">
<h1>Settings</h1>
<br>
<input type="text" placeholder="background color" id="bgc">
<br>
<input type="button" onclick="changeSettings()" value="Change settings">
</div>
<script>
function changeSettings() {
if(loggedIn == true) {
if(typeof(Storage)!= "undefined") {
var backg = document.getElementById("bgc").value;
if(backg!="") {
localStorage.setItem("backgroundColor", backg);
document.body.style.background = localStorage.getItem("backgroundColor");
} else {
alert("Enter a color.")
}
} else {
alert("No support.")
}
} else {
alert("You must be logged in to do that.")
}
}
function loadSettings() {
if(typeof(Storage)!="undefined") {
document.body.style.background = localStorage.getItem("backgroundColor");
} else {
alert("No support.")
}
}
function signup() {
if(typeof(Storage)!= "undefined") {
var username = document.getElementById("textbox").value;
var password = document.getElementById("textbox2").value;
if(username!="" && password!="") {
localStorage.setItem("username", username);
localStorage.setItem("password", password);
} else {
alert("Please enter a valid username and password.")
}
} else {
alert("No support.")
}
}
function login() {
if(typeof(Storage)!= "undefined") {
var username = localStorage.getItem("username");
var password = localStorage.getItem("password");
var usernameInput = document.getElementById("textbox3").value;
var passwordInput = document.getElementById("textbox4").value;
if(usernameInput!="" && passwordInput!="") {
if(usernameInput == username && passwordInput == password) {
document.getElementById("result").innerHTML = "Logged in!";
loggedIn = true;
loadSettings();
} else {
document.getElementById("result").innerHTML = "Wrong password/username!";
}
} else {
alert("Please enter a valid username and password.")
}
} else {
alert("No support.")
}
}
</script>
</body>
</html>
ps: sorry if it's messy :p
You should probably be using SQL if you want to store user inputs such as Usernames and Passwords.
Hashing & Password Storage
Good video to watch if your trying to learn Databases!
:)
Not a good way to store the plain username/password in localStorage. anyone can change those value. Since you check the login using
localStorage.setItem("username", username);
localStorage.setItem("password", password);
var username = localStorage.getItem("username");
var password = localStorage.getItem("password");
usernameInput == username && passwordInput == password
This login condition can make true using different ways.
Found this article from the Google, Hope you'll get some idea to do in
secure way :)
I made register and login options in an empty html (not on a webpage) just to see if I could and how I could do it. Now I ran into a problem - I can register multiple usernames that have the same value (for example I can register "test username" as many times as I want to).
I want to know how I can check if the value that the user puts in to register has already been registered.
Here is my code :
HTML :
<!-- Login -->
<div class="login">
<label>Login</label>
<input type="text" id="login-username" class="textbox" placeholder="Username"/>
<input type="password" id="login-password" class="textbox" placeholder="Password"/>
<button type="submit" onclick="login()">Login</button>
</div>
<!-- Register -->
<div class="register">
<label>Register</label>
<input type="text" id="register-username" class="textbox" placeholder="Username"/>
<input type="password" id="register-password" class="textbox" placeholder="Password"/>
<button type="submit" onclick="register()">Register</button>
</div>
JavaScript :
function login() {
if(document.getElementById("login-username").value == username1 && document.getElementById("login-password").value == password1) {
alert("Hi " + username1 + " you are now logged in.");
} else if(document.getElementById("login-username").value == username2 && document.getElementById("login-password").value == password2) {
alert("Hi " + username2 + " you are now logged in.");
} else {alert("Wrong username or password");}
function register() {
if (username1 == null && password1 == null) {
localStorage.removeItem("username1");
localStorage.setItem("username1", document.getElementById("register-username").value);
localStorage.removeItem("password1");
localStorage.setItem("password1", document.getElementById("register-password").value);
alert("Hi, " + document.getElementById("register-username").value + " is now registered.");
location.reload();
} else if (username2 == null && password2 == null) {
localStorage.removeItem("username2");
localStorage.setItem("username2", document.getElementById("register-username").value);
localStorage.removeItem("password2");
localStorage.setItem("password2", document.getElementById("register-password").value);
alert("Hi, " + document.getElementById("register-username").value + " is now registered.");
location.reload();
}
var username1 = localStorage.getItem("username1");
var username2 = localStorage.getItem("username2");
var usernameAlpha = [username1, username2]; //This is a list of all usernames
//and it's what I want to look through when I'm checking if the value/username already exists
var password1 = localStorage.getItem("password1");
var password2 = localStorage.getItem("password2");
try this
function register(){
var users = JSON.parse(localStorage.getItem('users')) || [];
var username = document.getElementById("register-username").value;
var password= document.getElementById("register-password").value;
var toBeRegister= true;
for(i=0;i<users.length;i++){
if(users[i].username === username){
toBeRegister = false
}
}
if(toBeRegister){
users.push({username:username,password:password})
localStorage.setItem('users', JSON.stringify(users));
}
}
Thanks to Rajesh I was able to make it work and here is how :
I just used his method to check if the username that the user typed in was in usernameAlpha. If it was I displayed an alert message "Username taken" and if it was not I simply registered the user like normal.
Here is the code :
function register() {
if(usernameAlpha.indexOf(document.getElementById("register-username").value) > -1) {alert("Username taken")
} else if (username1 == null && password1 == null && document.getElementById("register-username").value != "" && document.getElementById("register-password").value != "") {
localStorage.removeItem("username1");
localStorage.setItem("username1", document.getElementById("register-username").value);
localStorage.removeItem("password1");
localStorage.setItem("password1", document.getElementById("register-password").value);
alert("Hi, " + document.getElementById("register-username").value + " is now registered.");
location.reload();
} else if (username2 == null && password2 == null && document.getElementById("register-username").value != "" && document.getElementById("register-password").value != "") {
localStorage.removeItem("username2");
localStorage.setItem("username2", document.getElementById("register-username").value);
localStorage.removeItem("password2");
localStorage.setItem("password2", document.getElementById("register-password").value);
alert("Hi, " + document.getElementById("register-username").value + " is now registered.");
location.reload();
}
}
You mention 'array', but don't use them well. You still have variables username1 and username2, which means you have to copy a bunch of code (again) if you want to introduce username3. If you build an array of users, or an object where the username is the key/propertyname, then you can build a more dynamic user database.
You can save and load the entire object in a serialized way to and from localStorage.
Do note that although it's a fun exercise, localStorage is not a safe place for this, and storing passwords (either in plain text or encrypted) is not a good practice either.
Anyway, it could look something like this:
var
userDatabase = null;
function loadUserDatabase() {
// Load the user database only if it wasn't loaded yet. This way, various functions can
// always call this function 'to be sure'.
if (userDatabase === null)
userDatabase = JSON.parse(localStorage.getItem("userDatabase"));
}
function saveUserDatabase() {
// Save the entire database back to local storage.
localStorage.setItem("userDatabase", JSON.stringify(userDatabase));
}
function normalizeUsername(username) {
// "Normalize" the username by converting different styles of writing to
// a base form.
// In this case, trim and convert to lowercase to effectively make user
// names case insensitive while still usings keys/properties.
return username.trim().toLowerCase();
}
function findUser(username) {
// Check if user database is loaded
loadUserDatabase();
// Find the user by username.
username = normalizeUsername(username);
if (userDatabase.hasOwnProperty(username)) {
return userDatabase[username];
}
return false;
}
function isValidUsername(username) {
// Implement any limits you want (or need) to impose here.
// A length check of, say <1000 would be a nice addition.
return username != '';
}
function setUser(username, password) {
loadUserDatabase();
username = normalizeUsername(username);
// Set/overwrite the user
userDatabase[username] = {password: password};
// Save the database to disk.
saveUserDatabase();
}
function login() {
var username = document.getElementById("login-username").value;
var password = document.getElementById("login-password").value;
if (user = findUser(username)) {
if (user.password == password) {
// There is a match, log in
alert('login successful as user ' + username);
} else {
// Password incorrect
alert('Invalid password for username ' + username);
}
} else {
// User not found
alert('User ' + username + ' not found');
}
}
function register() {
var username = document.getElementById("register-username").value;
var password = document.getElementById("register-password").value;
if (!isValidUsername(username)) {
alert('invalid username')
} else if (user = findUser(username)) {
alert('user ' + username + ' already exists');
} else {
setUser(username, password);
alert('user ' + username + ' created');
}
}
<!-- Login -->
<div class="login">
<label>Login</label>
<input type="text" id="login-username" class="textbox" placeholder="Username"/>
<input type="password" id="login-password" class="textbox" placeholder="Password"/>
<button type="submit" onclick="login()">Login</button>
</div>
<!-- Register -->
<div class="register">
<label>Register</label>
<input type="text" id="register-username" class="textbox" placeholder="Username"/>
<input type="password" id="register-password" class="textbox" placeholder="Password"/>
<button type="submit" onclick="register()">Register</button>
</div>
use the toString method from Object.prototype.
if( Object.prototype.toString.call( Variable ) === '[object Array]' ) {
alert( 'Array!' );
}
I'm trying to make an array that saves to local storage and the user can sort the items, add an item, delete an item, and clear the local storage. I'm having a lot of trouble getting the delete or splice user input to work can someone please provide me with some advice.
This is the code I have so far please forgive me if it's bad, definitely keen to know how it can be made better.
...
<script>
//lets my program know the books1 variable is an array
var books1 = []
//lets my program know the result variable is a string
var result = ""
//checks to see if the localstorage key booksArray exists, if it doesn't books1 has 3 books added ans is stored locally with a key of booksArray
if (localStorage.getItem("booksArray") == null) {
books1 = ["book1", "book2", "book3", "m", "p"]
localStorage.setItem("booksArray", JSON.stringify(books1))
// var theArray = JSON.parse("booksArray")
}
else {
loadBooks(); //loads the books to an array with variable name listBooks
}
function loadBooks() {
var result = localStorage.getItem("booksArray")
var listBooks = JSON.parse(result)
}
function sortBooks() {
var sortedBooks1 = localStorage.getItem("booksArray")
var sortedBooks2 = JSON.parse(sortedBooks1)
// loadBooks may work but haven't got it to yet. try redoing the project on books Array 2.2
sortedBooks2.sort()
document.getElementById("display1").innerHTML = sortedBooks2
localStorage.setItem("booksArray",JSON.stringify(sortedBooks2))
}
function addBook() {
var test1 = localStorage.getItem("booksArray")
var addedBook = document.getElementById("inputData").value
var addedBook2 = JSON.parse(test1)
addedBook2.push(addedBook)
document.getElementById("display1").innerHTML = addedBook2
localStorage.setItem("booksArray", JSON.stringify(addedBook2))
}
function delBook() {
//if (document.getElementById("inputData").value.length > 0) {
var local = localStorage.getItem("booksArray")
var delItem = document.getElementById("inputData").value
var array = JSON.parse(local)
var x = array.indexof(delItem);
//test2.splice(delItem,1)
if (delItem != -1) {
delete booksArray[delItem]
}
document.getElementById("display1").innerHTML = test2
}
// my test function
/* function displaybooks() {
var test1 = localStorage.getItem("booksArray")
var test2 = JSON.parse(test1)
document.getElementById("display1").innerHTML = test2[2]
}
*/
function clearLocal() {
localStorage.clear()
}
</script>
...
<body>
<!--i need to make the page so onload it displays the books--->
<form>
<input type="text" id="inputData" />
</form>
<input type="button" onclick="delBook()" value="delete your books" />
<input type="button" onclick="sortBooks()" value="test me" />
<input type="button" onclick="addBook()" value="add your book" />
<input type="button" onclick="clearLocal()" value="clear local storage" />
<p id="display1"></p>
</body>
</html>
You Can Try This Code For CRUD Operation For JSON data
$(function(){
var operation = "A"; //"A"=Adding; "E"=Editing
var selected_index = -1; //Index of the selected list item
var tbClients = localStorage.getItem("tbClients");//Retrieve the stored data
tbClients = JSON.parse(tbClients); //Converts string to object
if(tbClients == null) //If there is no data, initialize an empty array
tbClients = [];
function Add(){
var client = JSON.stringify({
ID : $("#txtID").val(),
Name : $("#txtName").val(),
Phone : $("#txtPhone").val(),
Email : $("#txtEmail").val()
});
tbClients.push(client);
localStorage.setItem("tbClients", JSON.stringify(tbClients));
alert("The data was saved.");
return true;
}
function Edit(){
tbClients[selected_index] = JSON.stringify({
ID : $("#txtID").val(),
Name : $("#txtName").val(),
Phone : $("#txtPhone").val(),
Email : $("#txtEmail").val()
});//Alter the selected item on the table
localStorage.setItem("tbClients", JSON.stringify(tbClients));
alert("The data was edited.")
operation = "A"; //Return to default value
return true;
}
function Delete(){
tbClients.splice(selected_index, 1);
localStorage.setItem("tbClients", JSON.stringify(tbClients));
alert("Client deleted.");
}
function List(){
$("#tblList").html("");
$("#tblList").html(
"<thead>"+
" <tr>"+
" <th></th>"+
" <th>ID</th>"+
" <th>Name</th>"+
" <th>Phone</th>"+
" <th>Email</th>"+
" </tr>"+
"</thead>"+
"<tbody>"+
"</tbody>"
);
for(var i in tbClients){
var cli = JSON.parse(tbClients[i]);
$("#tblList tbody").append("<tr>"+
" <td><img src='edit.png' alt='Edit"+i+"' class='btnEdit'/><img src='delete.png' alt='Delete"+i+"' class='btnDelete'/></td>" +
" <td>"+cli.ID+"</td>" +
" <td>"+cli.Name+"</td>" +
" <td>"+cli.Phone+"</td>" +
" <td>"+cli.Email+"</td>" +
"</tr>");
}
}
$("#frmCadastre").bind("submit",function(){
if(operation == "A")
return Add();
else
return Edit();
});
List();
$(".btnEdit").bind("click", function(){
operation = "E";
selected_index = parseInt($(this).attr("alt").replace("Edit", ""));
var cli = JSON.parse(tbClients[selected_index]);
$("#txtID").val(cli.ID);
$("#txtName").val(cli.Name);
$("#txtPhone").val(cli.Phone);
$("#txtEmail").val(cli.Email);
$("#txtID").attr("readonly","readonly");
$("#txtName").focus();
});
$(".btnDelete").bind("click", function(){
selected_index = parseInt($(this).attr("alt").replace("Delete", ""));
Delete();
List();
});
});
body{
font-family:Tahoma;
}
ul{
list-style:none;
}
ul label{
width:100px;
float:left;
}
#frmCadastre{
border:solid 1px;
}
#tblList{
width:100%;
border:solid 1px;
text-align:left;
border-collapse:collapse;
}
#tblList tbody tr{
border:solid 1px;
height:30px;
}
#tblList thead{
background:beige;
}
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
</head>
<body>
<form id="frmCadastre">
<ul>
<li>
<label for="txtID">ID:</label>
<input type="text" id="txtID"/>
</li>
<li>
<label for="txtName">Name:</label>
<input type="text" id="txtName"/>
</li>
<li>
<label for="txtPhone">Phone:</label>
<input type="text" id="txtPhone"/>
</li>
<li>
<label for="txtEmail">Email:</label>
<input type="text" id="txtEmail"/>
</li>
<li>
<input type="submit" value="Save" id="btnSave"/>
</li>
</ul>
</form>
<table id="tblList">
</table>
</body>
</html>
try this clearLocal method and change(correct) in indexOf
function delBook() {
var x = array.**indexOf**(delItem);
}
function clearLocal() {
localStorage.clear()
document.getElementById("display1").innerHTML = "";
}
The local storage API contains a method for removing a single item: removeItem( key). So to delete your delItem you want to do:
localStorage.removeItem(delItem);
I have a login form that, when completed, sends users to a page with a JavaScript generated URL (allowing me to pass a JavaScript variable to my PHP script using $_GET). However, in order to do that, the Login button is currently 'type="button"'. While everything works, it means that users cannot login by hitting Enter; they must actually click the Login button. Is there a way I can "Submit" the form, while still having it point to the JavaScript generated URL?
This seems like a pretty basic concept, which tells me I might be approaching it the wrong way to begin with. Any guidance is appreciated.
HTML:
<form name="login">
Username: <input type="text" name="user_id"/>
Password: <input type="password" name="pswrd"/>
<input type="button" onclick="check(this.form)" value="Login"/>
</form>
JavaScript:
function check(form) {
var userCredentials = [["jsmith", "smithpassword", "John Smith"], ["jdoe", "doepassword", "Jane Doe"]];
var credCheck = 0;
for (var i = 0; i < userCredentials.length; i++) {
if (userCredentials[i][0] == form.user_id.value) {
credCheck += 1;
var displayName = userCredentials[i][2];
if (userCredentials[i][1] == form.pswrd.value) {
window.open("home.php?display_name=" + displayName, "_self");
} else {
alert('The username and password do not match.');
return false;
}
}
}
if (credCheck == 0) {
alert('The username entered is not valid.');
return false;
} else {
return true;
}
}
Instead of opening php page via javascript, you need to change the form action dynamically to point to your generated url.
HTML:
<form name="login">
Username: <input type="text" name="user_id"/>
Password: <input type="password" name="pswrd"/>
<input type="submit" onclick="check(this.form)" value="Login"/>
</form>
JavaScript: (line 9 & 10 changed)
function check(form) {
var userCredentials = [["jsmith", "smithpassword", "John Smith"], ["jdoe", "doepassword", "Jane Doe"]];
var credCheck = 0;
for (var i = 0; i < userCredentials.length; i++) {
if (userCredentials[i][0] == form.user_id.value) {
credCheck += 1;
var displayName = userCredentials[i][2];
if (userCredentials[i][1] == form.pswrd.value) {
form.action = "home.php?display_name=" + displayName;
return true;
} else {
alert('The username and password do not match.');
return false;
}
}
}
if (credCheck == 0) {
alert('The username entered is not valid.');
return false;
} else {
return true;
}
}
You could try:
<form name="login" onsubmit="check(this)">
Username: <input type="text" name="user_id"/>
Password: <input type="password" name="pswrd"/>
<input type="submit" value="Login"/>
</form>