Javascript Confirmation Message Condition - javascript

I need to create a condition to show confirmation message to validate if a session is existing in the site before logging in.
If user is currently logged in the site with the same username / credential or if session is existing then it will call the confirmation message and execute the action after clicking OK.
How do I create the condition before calling the confirmation message?
function checkSession()
{
//call SQL
varSQL = "Select * from user_table where user = 'user'";
objCmd.ActiveConnection = objCon;
objCmd.CommandText = varSQL;
objCmd.CommandType = 1;
objRec = objCmd.Execute();
var user = objRec("user");
if (if user is not null)
{
return confirm("Please click OK to terminate the session and proceed to login.");
}
}
<input type="submit" value="Login" onclick="return checkSession()"/>
It doesn't work if I try to add another condition on the confirmation function which is checking from database

Related

Form submitting, even when AJAX form check returns false

I have a really simple login form that I want to check if the credentials are right (so I don't have to reload a page if the credentials are wrong) before submitting the form.
The problem I'm running into is the response from the AJAX call. When the program decides that the user has supplied the correct credentials, this code works like a charm. In addition, when performing the two checks prior to the AJAX call (whether the user filled in the password input field or if the username is valid), the code works perfectly. It returns an error message and returns the false boolean value, preventing the form from submitting. But, when the response from the server comes back and it is found that the credentials are not correct, the error message displays, but the page also reloads (therein displaying an additional error message). Why is the form still submitting, even though I'm returning false? I've checked the JavaScript console, there are no errors. I've also tried inverting the if statement, checking if ajax.responseText === "true", to the same result. I've tried adding a return false beneath the ajax.onreadystatechange call, but that just prevents the form from submitting at all (regardless of the response from the server).
Here is the form code:
<form method="POST" action="/afton/" onsubmit="return checkForm()">
<label for="username">Username:</label>
<input type='text' id='username' name='username' placeholder='Enter username...' required>
<label for="password">Password:</label>
<input type='password' id='password' name='password' placeholder='Enter password...' required>
<div class="form-buttons">
<button type='submit' name='action' id="loginButton" value='login'>Login</button>
<button type='button' id='register'>Register</button>
</div>
</form>
Here is the js function:
// Function that checks whether the user supplied correct credentials
function checkForm() {
// Get the password provided and the server message div on the page
const messageBox = document.getElementById("server-message");
const password = document.getElementById("password").value;
// If password is blank, return error message and return false
if (password === "") {
messageBox.innerHTML = "<p class='badMessage'>Please fill in the password!</p>"
return false;
}
// If the username input tag doesn't contain the 'goodBorder' class received upon validation of username, return error and false
if (!usernameInput.classList.contains("goodBorder")) {
messageBox.innerHTML = "<p class='badMessage'>Please provide a valid username!</p>"
return false;
}
// AJAX call that posts the info via JSON to check
const ajax = new XMLHttpRequest();
ajax.open("POST", "index.php?action=ajaxLogCheck", true);
ajax.setRequestHeader("Content-type", "application/json");
ajax.send(JSON.stringify({"username":usernameInput.value, "password":password}));
// Handles the AJAX response
ajax.onreadystatechange = function () {
if (ajax.readyState === 4 && ajax.status === 200) {
if (ajax.responseText !== "true") {
messageBox.innerHTML = ajax.responseText;
return false;
}
return true
}
}
}
And here is the PHP code that handles the AJAX:
// Get posted JSON encoded data
$data = json_decode(trim(file_get_contents("php://input")), true);
// Filter and sanitize the supplied username and password
$username = filter_var($data['username'], FILTER_SANITIZE_STRING);
$password = filter_var($data['password'], FILTER_SANITIZE_STRING);
// Get user data by the username and check the username against the password
$userData = getClient($username);
$hashCheck = password_verify($password, $userData['password']);
// Check response from the hashCheck and return the result
if ($hashCheck) {
echo "true";
exit;
}
logAtt($username, $_SERVER['REMOTE_ADDR'], false, getBrowser($_SERVER['HTTP_USER_AGENT']));
sleep(0.5);
$rands = array("Sorry, the username and/or password doesn't match our database. Please try again.", "Sorry, we don't recognize those login credentials. Please try again.", "Sorry, that login was incorrect. Please try again.", "Incorrect, please try again");
$randResult = array_rand(array_flip($rands));
echo "<p class='badMessage'>$randResult</p>";
// Just the point in AJAX function where you were returning True or
// False...Just Assign RESULT = 0 for False and
// RESULT = 1 for True
// .....SUppose You password matches so you were returning True..
// Dont do that...Instead Just Assign RESULT = 0 in that place and
// and out of the ajax Block paste this 'return Boolean(RESULT)'
// if RESULT = 0 then it will return False else it will return True
// Function that checks whether the user supplied correct credentials
function checkForm()
{
// Initialize a Variable Here Say RESULT
var RESULT = 0;
if (password === "")
{
RESULT = 0;
}
else if (!usernameInput.classList.contains("goodBorder"))
{
messageBox.innerHTML = "<p class='badMessage'>Please provide a valid username!</p>"
RESULT = 0;
}
// After this Put the ajax function and if you want to return False
// then simply assign RESULT = 0 instead of 'return false' else assign
// RESULT = 1 instead of 'return true'
return Booelan(RESULT);
// THis line is main Part this is returned by checkForm() function
}
// If I am still not clear, then I'll be happy to explain it on Google Meet.! :)

Ajax dependent text field and dropdown menu (Php and Javascript)

I'm a student and still new with Javascript and php, i need to make a login page for my website that can check user input in the database using ajax.
Example: When the user enter their username and password into the field given,the system will automatically check in database either the user exist or not and return the data needed such as user responsibilty from the response table to the dropdown menu below, then they can login into the system.
Below is my basic coding:
Config.php:
e$host = "localhost";
$User = "root"
$Pass = "passw";
$db = "skm_spm";
Login.php:
<?
require ("config.php");
$conn=mysqli_connect($host,$user,$pass,$db);
$duser="select * from tab_user where user_name = '".$_POST["Lname"]."'";
$uresult=myqli_query($conn,$duser);
if(!$uresult)
die("Invalid query: ".mysqli_error());
else
if(mysqli_num_rows($uresult)== 0){
echo "User does not exist";
}
else
{
$row=mysqli_fetch_array($result,MYSQL_BOTH);
if($row["User_Password"] == $_POST["Lpass"])
{
$dresp="select resp_id,resp_name from tab_resp";
$result2 = mysqli_query($conn,$dresp);
}
else
{
}
}
?>
<html>
<b>Login</b><br>
Name : <input type = "text" name="Lname" id="Lname" placeholder="Username"/><br>
Password: <input type = "password" name="Lpass" id="Lpass" placeholder="password"/><br><br>
<div class = "optresp">
<select name="sresp" id="sresp">
<option>--Responsibility--</option>
<?
while (mysqli_fetch_array($result2)){
echo "<option value='$row[1]'>$row[1]</option>";
?>
</select>
</div>
</html>
I have learn on internet and try to code with my understanding,but still failed. I need a php ajax coding that can work with code above.
Thank you.
I will provide you with some code from my recent project and hopefully you will be able to understand it and adapt it to your needs.
Firstly, you should have the login form in a separate file to the PHP login code. Then have button on the page or an enter events that run a Javascript function, in my case Login(). In this Javascript function the text within the input fields are saved to two variables and some basic checks are done on them to ensure that they have been filled in. Next, the PHP login function file (it has no visible content in just processes some data in PHP) using the $.post line. This also passed the two input variables (under the same name) to the PHP file. You can also see that depending on what is returned/echoed from the PHP file as "data" several possible outcomes may occur (Login Success, Account Banned or Invalid Login). I personally call these outcomes error messages or success messages, for example error message 6 for incorrect password/username.
//FUNCTIONS
function Login(){
var StrUsername = $("#txtUsername" ).val();
var StrPassword = $("#txtPassword").val();
if (StrUsername == "" && StrPassword == ""){
$('#pError').text('Enter your Username and Password!');
}
else if(StrUsername == ""){
$('#pError').text('Enter your Username!');
}
else if(StrPassword == ""){
$('#pError').text('Enter your Password!');
}
else{
$.post('https://thomas-smyth.co.uk/functions/php/fnclogin.php', {StrUsername: StrUsername, StrPassword: StrPassword}, function(data) {
if (data == 0){
window.location.href = "https://thomas-smyth.co.uk/home";
}
else if (data == 1){
window.location.href = "https://thomas-smyth.co.uk/banned";
}
else if (data == 6){
$('#pError').text('Username & Password combination does not exist!');
}
});
}
}
Next the PHP function file. Firstly, the variables passed by the Javascript are collected using $_POST. My SQL class is then pulled into the file, this does all my SQL DB connections. I then have my SQL statement that will search to see if the account exists. Notice the ? in it. This prevents SQL injections as the variables is bound into the statement through the SQL server meaning it won't allow people to put SQL code within my input fields to break my database. I then check whether the account exists, if it doesn't I save data to 6, which will cause the error message 6 in the Javascript to run when data is returned. I have a field in my database that contains a rank. If the login is correct then I create a SESSION variable to store their username and rank in. This is later used on pages to check whether they are logged in before displaying a page (this speeds up navigation as it means that the DB doesn't need to be searched everytime the user switches page, however does bring some issues like if you ban a user while they are logged in they will stay logged in until their session dies). You could use this on your dropdown menu to ensure the user is logged in and/or get their username. Finally, I return 0 or 1, so that the Javascript then re-directs them to the correct page.
<?php
//Retrieves variables from Javascript.
$StrUsername = $_POST["StrUsername"];
$StrPassword = $_POST["StrPassword"];
require "sqlclass.php";
$TF = new TF_Core ();
$StrQuery = "
SELECT Username, Rank FROM tblUsers
WHERE Username = ? AND Password = ?";
if ($statement = TF_Core::$MySQLi->DB->prepare($StrQuery)) {
$statement->bind_param('ss',$StrUsername,$StrPassword);
$statement->execute ();
$results = $statement->get_result ();
if($results->num_rows == 0){
$data = 6;
}
else {
while ($row = $results->fetch_assoc()) {
//Other groups
if ($row["Rank"] == "Developer" || $row["Rank"] == "Staff" || $row["Rank"] == "Cadet"){
session_start();
$_SESSION["LoginDetails"] = array($StrUsername, $row["Rank"]);
$data = 0;
}
//Banned
else if ($row["Rank"] == "Banned"){
session_start();
$_SESSION["LoginDetails"] = array($StrUsername, "Banned");
$data = 1;
}
}
}
}
echo $data;
?>
Hopefully this helps you. Please say if you need more help!
You need to make ajax call on blur of username to check if user exists in database and on success of that you can make one more ajax to check for password match of that particular user. This will give you both cases whether a user exixts or not if exixts then does the password match or not only after that user will be logged in and then you can show the responsibilities of that particular user.
For username:
$('#Lname').blur(function(){
$.ajax({
url:'url where query for matching username from database',
data:'username collected from input on blur',
type:'POST',
success:function(data){
//Code to execute do on successful of ajax
}
})
})
For Password:
The ajax call remains the same only url, data and response changes

How to fix my login issue with local storage?

Basically I have 2 files... register.html and login.js.... I am able to store user's registration details into local storage and then parsed it as objects in array.... I need to log in properly(when user and pass match, alert box indicates login successful and then PHP file will redirect user, and if no match, alert box will indicate for that separately) and then second alert box as you have successfully signed in and then it will not redirect me as the PHP file is meant to do so when the user and pass match local storage... Any clues??
You are just not iterating correctly through credentials, you have to wait until you are sure that the current login credentials are not equal to any of the stored credentials, so you have to get this part of code out of the for loop:
alert('Invalid Username or Password! Please try again.');
event.preventDefault();
window.location="Login.html";
try this code for validating the login:
function validlogin(event) {
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
var entriesJSON = localStorage.getItem('allEntries');
if (!entriesJSON) {
event.preventDefault();
alert("Nothing stored!");
return;
}
var allEntries = JSON.parse(entriesJSON);
var isCorrectCredentials=false;
for (var i = 0; i < allEntries.length; i++) {
var entry = allEntries[i];
var storedUserName = entry.user;
var storedPassWord = entry.pass;
var storedEmailAddress = entry.email;
if (username == storedUserName && password == storedPassWord) {
isCorrectCredentials=true;
alert("Successfully logged in!");
return;
} }
if(!isCorrectCredentials){
alert('Invalid Username or Password! Please try again.');
event.preventDefault();
window.location="Login.html";
}
}
this way you will login if the current username and password are correct and notify the rest of the code using:
isCorrectCredentials=true;
that the login info was true and you are successfully logged in.
and the part of code that should be executed if the login info is not true will be executed 1 time max.

Redirect on deny of a confirm dialog

My task is to submit a from based on user confirmation. If the user confirm then the form is submitted. If the user deny then the from is redirected to other page. I've a form in jsp like this -
.....
<form id="stageUpdateForm" method="post">
</form>
......
And in javascript I'm trying -
$('#stageUpdateForm').submit(function() {
decision = confirm("Some data changed. Are you sure?");
return decision;
// if user deny then redirect
});
Now if the user deny to submit the from its stay in current page. But I want to redirect the page to other url (eg. - www.google.com) if the user deny. How can I do this?
You want to try something like this:
if (decision) {
window.location = "http://whenever.wherever";
} else {
// Returning false from a submit handler will prevent the submit action.
return false;
}
You can do:
$('#stageUpdateForm').submit(function () {
var decision = confirm('Some data changed. Are you sure?');
// if user deny then redirect
if (!decision) {
$(location).attr('href', 'http://www.google.com');
}
// If user confirm, than it will return true and the form will be sumbited
return decision;
});

How to create a remember me function in login without using form in javascript or jquery

I'm almost done with my project, but the specifications for my login is not yet 100% done. Remember me function is not yet working.
HTML
<input type="text" id="signinId" class="email-input" placeholder="Email">
<input type="password" id="signinPwd" class="password-input" placeholder="Password">
<input id="rememberChkBox" type="checkbox">
<button id="Sign" class="button">Login</button>
Jquery Script
$(document).ready(function(){
$("#Sign").click(function(){
//Script for login is here...
});
});
I am not using form in this login page.
The specs is that when the checkbox is checked upon login, the user must be remebered. Once he logout, the textbox should be empty and when clicked on the #signinId input his username must be displayed.
It should look like this, if it is possible:
Sceenshot 1:
When email input is clicked
Screenshot 2: Autofill
Any help is very much appreciated.
Thank you in advance.
Auto Login system.
'Remember me' is not actually used to display user name and password on the login form because this feature is already provided by any browser. But it is intended for automatic login when users revisit the web.
To make auto login system without storing login credential on cookie is by adding database table that store userid and login_string.
Insert/Update the login_string every user login.
And when user login using remember me (press the radio button), then store the login_string on the cookie.
-------------------------------------------------------------------
id (ai) | userid | login_string (128 chars)
--------------------------------------------------------------------
1 | 1 | 86faabe4142269e2274df911a....
--------------------------------------------------------------------
2 | 2 | 013835e194d75c183dc914c9e....
Login_string must be a unique string and can be created by this way :
$login_string = hash('sha512', $userid . $_SERVER['HTTP_USER_AGENT'] . time());
The result is a unique 128 string length.
To store login_string on the cookie :
if(isset(post('remember_me')) {
$cookie_name = 'user_str_session';
$cookie_value = $login_string;
setcookie($cookie_name, $cookie_value, time() + (86400 * 1), "/"); // one day example
}
Next time the user close the browser and revisit the web ( where normally login session has expired ), then at the first page load, system will find the login_string and return the userid. By using this userid, system will create login session for automatic login.
Example script :
if(!isset($_SESSION['id'])) {
if(isset($_COOKIE['user_str_session'])) {
$user_string = $_COOKIE['user_str_session'] ;
$sql = "SELECT `userid` FROM `users_log` WHERE `string` =? ";
$query = $this->db->query($sql, $user_string);
$userid = $query->row()->userid;
if($userid) {
$_SESSION['id'] = $userid;
}
}
}
To prevent the login_string on a public computer, apply user logout by deleting the login_string on cookie.
function logout()
{
// remove cookie
setcookie("user_str_session", "", time() - 3600, "/");
session_destroy();
redirect('/');
}
This is only a brief description to create an automatic login system. Practically you can play with your own style and needs.
Its working perfectly for me..
You need Jquery.cookie.min.js..
$(function () {
if (localStorage.chkbox && localStorage.chkbox != '') {
$('#rememberChkBox').attr('checked', 'checked');
$('#signinId').val(localStorage.username);
$('#signinPwd').val(localStorage.pass);
} else {
$('#rememberChkBox').removeAttr('checked');
$('#signinId').val('');
$('#signinPwd').val('');
}
$('#rememberChkBox').click(function () {
if ($('#rememberChkBox').is(':checked')) {
// save username and password
localStorage.username = $('#signinId').val();
localStorage.pass = $('#signinPwd').val();
localStorage.chkbox = $('#rememberChkBox').val();
} else {
localStorage.username = '';
localStorage.pass = '';
localStorage.chkbox = '';
}
});
});
When login form has been sumbitted check the checkbox, if it has been checked, store the login form data including username and password in a related cookie. the next time a user comes to the page you can read the cookie, if it is set fill the form with the stored data.
this fiddle can help you:
https://jsfiddle.net/wrvnsst2/
you can use the below link to learn how to work with cookies in jquery:
http://www.sitepoint.com/eat-those-cookies-with-jquery/
some codes to explain more:
$(document).on(ready,function(){
fillByMemory()
$('button#sign').on('click',function(){
if($('#rememberChkBox').val()){
rememberMe();
}
doLogin();
});
});
function rememberMe(){
$.cookie('id',$('#signinId').val());
$.cookie('pass',$('#signinPwd').val());
}
function fillByMemory(){
if(!!$.cookie('id'))
$('#signinId').val($.cookie('id'));
if(!!$.cookie('pass'))
$('#signinPwd').val($.cookie('pass'));
}

Categories

Resources