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
Related
I am creating a small CRUD web app where I need the user to enter their password when they wish to delete an item from the database, I have an onClick() on the delete button on the HTML table which passes the ID of the product to be deleted to the js function.
When the function runs I wish to confirm that they really want to delete the product and then ask for their password and store it in a cookie. BUT IT DOES NOT SEEM TO WORK :(
I am setting a cookie using javascript like
document.cookie = 'password=${userPassword},expires=${now.toGMTString()},path=/../includes/delete-product.inc.php;
With this line of code, when I console.log(document.cookie), it shows me the cookie in the console like
password=admin,expires=Sat, 12 Dec 2020 08:40:38 GMT,path=/../includes/delete-product.inc.php; PHPSESSID=3n1l3q6ksqitdpc76hjrero9ja
when I redirect to another PHP page using window.open() I can not access this cookie.
print_r($_COOKIE); <- only shows me the PHPSESSID only.
When I explicitly try to access the cookie using the following line
$userPassword = $_COOKIE[password]; it gives me undefined index 'password'
This is my code.
myproject/admin/view-products.php (This is the page where I try to set the cookie using javascript)
function deletePrompt(id) {
const now = new Date();
const time = now.getTime();
const expiresIn = time + (50 * 1000);
now.setTime(expiresIn);
const path = `../includes/delete-product.inc.php`;
const intent = confirm("Are you sure you want to delete this products");
if (intent === true) {
const userPassword = prompt("Enter password");
document.cookie = `password=${userPassword},expires=${now.toGMTString()},path=/../includes/delete-product.inc.php`;
console.log(document.cookie);
return;
window.open(`../includes/delete-product.inc.php?id=${id}`, "_self");
}
}
myproject/includes/delete-product.inc.php (This is the PHP page where I need to access the cookie)
<?php
require_once "./database-connection.inc.php";
require_once "./functions.inc.php";
if (isset($_SESSION["adminId"])) {
$productId = $_GET["id"];
$userPassword = $_COOKIE["password"]; //<- This throws undefined index error
if (deleteProduct($connection, $productId, $userPassword)) {
header("location: ../admin/view-products.php?msg=deleted");
exit();
}
else {
header("location: ../admin/view-products.php?msg=incorrectPass");
exit();
}
}
else {
header("location: ../admin/login.php");
exit();
}
To anyone else facing this the problem, the solution is that cookies don't get sent across directories, so you need to have the recipient file in the same domain if you wish to transfer cookies across them otherwise it won't work.
eg.
Following pattern will work
youProject/someDirectory/file1
youProject/someDirectory/file2
Following will NOT WORK
youProject/someDirectory/file1
youProject/someOtherDirectory/file2
I am working with HTML, PHP, jQuery.
In HTML Form with input type button I am sending data to jQuery and with post I am send to PHP file and then inserting in the database, the problem in my scenario is that in JavaScript file I am just getting else part of the code, the else part is "Enter Your Details Correctly" and data is not inserted in the database, and also page redirect is not working in both success or failure of data insertion. I will really appreciate your time if you guys can help.
On different project my data is inserted in the database but page redirect not working, for page redirect I tried window.location.href, window.location.replace.
$(document).ready(function() {
"use strict";
$("#submit").click(function() {
var name = $("#name").val();
var email = $("#email").val();
var contact = $("#contact").val();
var gender = $("input[type=radio]:checked").val();
var msg = $("#msg").val();
if(name ===''|| email===''|| contact===''|| gender===''|| msg==='') {
alert("Insertion Failed Some Fields are Blank....!!");
}
else {
$.post(
"contactsave.php",
{ name: name, email: email, contact: contact,gender:gender, msg:msg},
function(data) {
if(data.message==='success')
{
window.location.replace("http://multimighty/contactthankyou.php");
}
else
{
alert("Enter Your Details Correctly");
}
},
'json');
}
});
});
/*contactsave.php*/
<?php
$name=$_POST['name'];
$email=$_POST['email'];
$contact=$_POST['contact'];
$gender=$_POST['gender'];
$msg=$_POST['msg'];
$sql = "INSERT INTO test(name, email, phone, gender, message) VALUES ('$name','$email','$contact','$gender','$msg')";
if ($con->query($sql) === TRUE) {
echo json_encode(array("message"=>"success"));
} else {
echo json_encode(array("message"=>"failuer".$con->error));
}
$con->close();
exit;
?>
I just want a simple form insertion without page refresh and after that page redirect
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'));
}
I am finishing up a form for user registration, and I wanted to know how to clear messages generated dynamically by AJAX, when the user clears the input (backspace). For example, let's say they enter a valid input, but then clear it with all backspaces - my code currently shows the valid input message, but I want that to switch to an empty string / no message when that happens:
if ($nameCheckCount < 1) {
if (preg_match("/^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/", $email)) {
echo 'This email is available.';
exit();
} else {
echo 'You entered an email with an invalid format.';
exit();
}
} else {
echo 'This email is taken.';
exit();
}
Is there some way I can change the above code I currently have to clear the message if there is no input after a backspace?
Secondly, once all the input is validated (I have one main HTML file for the form, and then three PHP files to check username, password, and email validity through the use of MySQL, or in the case of the passwords, a simple string match), can I set some sort of flag to then allow the user to submit? For example, the code that checks the email is as such:
function checkEmail() {
"use strict";
var status = document.getElementById("email_status");
var email = document.getElementById("email").value;
if (!(email == "")) {
status.innerHTML = "Checking...";
var request = new XMLHttpRequest();
request.open("POST", "email_check.php", true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
status.innerHTML = request.responseText;
}
}
var verify = "emailToCheck=" + email;
request.send(verify);
}
}
This is within my HTML file with the form. Once all fields are validated, is there a way to then allow the user to submit? One user may only have a unique combination of the username and email fields which are stored in the user table along with other data, and no username can be associated with multiple usernames, and vice versa. Thank you in advance for any tips!
I have been programming a registration form with ajax validation. The way I have it set up is in my js file, I have listeners that fire when the content of the field is changed. They send the data to the server, and the server makes sure it's valid and sends back its response in the form of a JSON object. I then read the values of the JSON object to output potential error messages.
I won't copy and paste the entire files, just one example:
$(document).ready(function() {
// USERNAME VALIDATION LISTENER
$("#regUsername").change(checkName);
}
and then the checkName function looks like this, it sends my ajax request:
function checkName() {
$.ajax({
type: "POST",
url: "./ajax_register.php",
data: {
request: "nameAvail",
username: $("#regUsername").val()
},
success: function(data) { // execute on success
var json = jQuery.parseJSON(data);
if (json.success) { // if usernames do match
$("#usernameAvailiability").removeClass().addClass('match');
$("#usernameAvailiability").text(json.msg);
} else { // if the user has failed to match names
$("#usernameAvailiability").removeClass().addClass('nomatch');
$("#usernameAvailiability").text(json.msg);
}
}
});
}
And depending on the response, it updates a span that tells the user if the input they wrote is valid or not.
The server validates with this part of the php file:
if(!isset($_POST['request'])) { // do nothing if no request was provided
print("no request provided");
} else { //ELSE request has been provided
if ($_POST['request'] == "nameAvail") { // if the request is to check if the username is valid
$response = array("success" => false, "msg" => " ", "request" => "nameAvail");
// CHECK USER NAME AVAILIABILITY CODE
if (!isset($_POST['username']) || empty($_POST['username'])) { // if no username is entered
$response['success'] = false;
$response['msg'] = "No username provided";
} else { // if a username has been entered
$username = $dbConn->real_escape_string($_POST['username']);
if (!ctype_alnum($username)) { // Make sure it's alpha/numeric
$response['success'] = false;
$response['msg'] = "username may only contain alpha numeric characters";
} elseif (strlen($username) < 4) { // make sure it's greater than 3 characters
$response['success'] = false;
$response['msg'] = "username must be at least 4 characters long.";
} elseif (strlen($username) > 20) { // make sure it's less than 26 characters
$response['success'] = false;
$response['msg'] = "username can be up to 20 characters long.";
} else { // make sure it's not already in use
$query = $dbConn->query("SELECT `id`, `username` FROM `users` WHERE `username` = '"
. $username . "' LIMIT 1");
if ($query->num_rows) { // if the query returned a row, the username is taken
$response['success'] = false;
$response['msg'] = "That username is already taken.";
} else { // No one has that username!
$response['success'] = true;
$response['msg'] = "That username is availiable!";
}
}
}
print(json_encode($response));
}
What I'd like to do now is create a function in my javascript for the register button. But I need to make sure all the forms are validated first.
I'm not sure what my options are. What I'd LIKE to do is somehow be able to recycle the code I've already written in my PHP file. I don't want to write out an entirely new if($_POST['request'] == "register") clause and then copy and paste all the validation code to make sure the input is valid before I insert the registrant's data into the database. It seems really repetitive!
I know I could check to see if all the spans on the page were set to 'match', but that could easily be tampered with and blank forms could be submitted.
so far, my register button function looks like this:
function register() {
if ( NEED SOME KIND OF CLAUSE HERE TO CHECK IF ALL THE FIELDS ARE VALID) {
$.ajax({
type: "POST",
url: "./ajax_register.php",
data: {
request: "register",
username: $("#regUsername").val(),
password: $("#regPassword").val(),
email: $("#email").val(),
dob: $("#dob").val(),
sQuest: $("#securityQuestion").val(),
sAns: $("#securityAnswer").val(),
ref: $("#referred").val()
}, success: function(data) {
var json = jQuery.parseJSON(data);
console.log(json);
$("#regValid").removeClass();
$("#regValid").text("");
}
}); //AJAX req done
} else {
$("#regValid").removeClass().addClass('nomatch');
$("#regValid").text("One or more fields are not entered correctly");
}
return false;// so that it wont submit form / refresh page
}
I would really appreciate some help, I've spent the last few hours scouring StackOverflow for an answer, but I can't seem to get anything to work. Will I have to duplicate code in my PHP file or is there a more elegant way to handle this?