Hi I am trying to validate email and username by using ajax but same code is not working for two different inupt fields.
HTML
<script>
//function to check username availability
function check_availability_username(){
//get the username
var username = $('.username').val();
//use ajax to run the check
$.post("check_username.php", { username: username },
function(result){
//if the result is 1
if(result == 1){
//show that the username is available
$('#username_availability_resul1').html('<span style="color:#0C0;">'+username + ' is available!</span>');
}else{
//show that the username is NOT available
$('#username_availability_result').html('<span style="color:#F00;">'+username +result+ ' already used!</span>');
}
});
}
function check_availability(){
//get the username
var email = $('.email').val();
//use ajax to run the check
$.post("check_email.php", { email: email },
function(result){
//if the result is 1
if(result == 1){
//show that the username is available
$('#email_availability_result').html('<span style="color:#0C0;">'+email + ' is available!</span>');
}else{
//show that the username is NOT available
$('#email_availability_result').html('<span style="color:#F00;">'+email + ' already used!</span>');
}
});
}
</script>
<form role="form" method="post" action="add-users.php?insert=ok" class="form-horizontal form-groups-bordered">
<div class="form-group">
<label for="field-1" class="col-sm-2 control-label">Username</label>
<div class="col-sm-6">
<input type="text" onkeyup="check_availability_username()" class="form-control" name="username" placeholder="Username1" required>
<div id='username_availability_result'></div>
</div>
</div>
<div class="form-group">
<label for="field-1" class="col-sm-2 control-label">Email Address</label>
<div class="col-sm-6">
<input type="email" onkeyup="check_availability()" class="form-control email" name="email" placeholder="Email Address" required>
<div id='email_availability_result'></div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-6">
<input type="submit" class="btn btn-primary" value="Add User">
<input class="btn btn-danger" type="reset" value="Reset">
</div>
</div>
</form>
check_username.php
<?php
//connect to database
$db = mysqli_connect('localhost', 'root', '123', 'mydb') or die('db not connected');
//get the username
$username = mysqli_real_escape_string($db, $_POST['username']);
//mysql query to select field username if it's equal to the username that we check '
$result = mysqli_query($db, 'select username from userinfo where username = "'. $username .'"');
//if number of rows fields is bigger them 0 that means it's NOT available '
if(mysqli_num_rows($result)>0){
//and we send 0 to the ajax request
echo 0;
}else{
//else if it's not bigger then 0, then it's available '
//and we send 1 to the ajax request
echo 1;
}
?>
check_email.php
<?php
//connect to database
$db = mysqli_connect('localhost', 'root', '123', 'mydb') or die('db not connected');
//get the email
$email = mysqli_real_escape_string($db, $_POST['email']);
//mysql query to select field email if it's equal to the email that we check '
$result = mysqli_query($db, 'select email from userinfo where email = "'. $email .'"');
//if number of rows fields is bigger them 0 that means it's NOT available '
if(mysqli_num_rows($result)>0){
//and we send 0 to the ajax request
echo 0;
}else{
//else if it's not bigger then 0, then it's available '
//and we send 1 to the ajax request
echo 1;
}
?>
code is working perfectly for EMAIL validation but not for USERNAME.
any suggestions
Related
index.php
This is the login form
<div class="modal-body">
<form action="loginPDO.php" method="post">
<?php if(isset($message))
{
echo '<label class="text-danger">'.$message.'</label>';
} ?>
<div class="form-group">
<label for="recipient-name" class="col-form-label">Username:</label>
<input type="text" name="username" id="username" placeholder="Enter Username" class="form-control">
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Password:</label>
<input type="password" name="password" id="password" placeholder="Enter Password" class="form-control">
</div>
<div class="form-group">
<button type="submit" name="login" id="login" class="btn btn-primary">Login</button>
<button type="button" class="btn btn-info">Register</button>
</div>
</form>
</div>
loginPDO.php
<?php
include 'dbconnection.php';
if(isset($_POST["login"]))
{
if(empty($_POST["username"]) || empty($_POST["password"]))
{
$message = '<label>All fields are required</label>';
header("location:index.php");
}
else
{
$query = "SELECT * FROM users WHERE username = :username AND password = :password";
$statement = $conn->prepare($query);
$statement->execute(
array(
'username' => $_POST["username"],
'password' => $_POST["password"]
)
);
$count = $statement->rowCount();
if($count > 0)
{
$_SESSION["username"] = $_POST["username"];
header("location:dashboard.php");
}
else
{
$message = '<label>Wrong Data</label>';
header("location:index.php");
}
}
}
?>
Hi Guys, I want to know how to display the alert message once the user inputs incorrect credentials
For example, Imagine the user inputs wrong credentials once the user clicks the login button it automatically appears the alert message above Username.
$message just exists in file loginPDO.php and ...
$message = '<label>Wrong Data</label>';
header("location:index.php");
Is not sufficient to pass the $message variable to index.php.
As said in comments you can try
// file loginPDO.php
$message = '<label>Wrong Data</label>';
header("location:index.php?error=" . urlencode("Wrong Data"));
// file index.php
<?php
$message = isset($_GET['error']) ? $_GET['error'] : null; // get the error from the url
if(!empty($message)) {
echo '<label class="text-danger">'.$message.'</label>';
} ?>
I am trying to make a website secure by using a hashed pasword and salt. I successfully implement it. But if users want to change their password it becomes difficult. How can I recode the change password I have so as to support hashedpassword and salt that I just implemented?
This is my changepassword form - change_password.php
<form method="post" id="change_password" class="form-horizontal">
<div class="control-group">
<label class="control-label" for="inputEmail">Current Password</label>
<div class="controls">
<input type="hidden" id="password" name="password" value="<?php echo $row['password']; ?>" placeholder="Current Password">
<input type="password" id="current_password" name="current_password" placeholder="Current Password">
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">New Password</label>
<div class="controls">
<input type="password" id="new_password" name="new_password" placeholder="New Password">
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Re-type Password</label>
<div class="controls">
<input type="password" id="retype_password" name="retype_password" placeholder="Re-type Password">
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" class="btn btn-info"><i class="icon-save"></i> Save</button>
</div>
</div>
</form>
This is my jQuery script
<script>
jQuery(document).ready(function(){
jQuery("#change_password").submit(function(e){
e.preventDefault();
var password = jQuery('#password').val();
var current_password = jQuery('#current_password').val();
var new_password = jQuery('#new_password').val();
var retype_password = jQuery('#retype_password').val();
if (password != current_password)
{
$.jGrowl("Password does not match with your current password ", { header: 'Change Password Failed' });
}else if (new_password != retype_password){
$.jGrowl("Password does not match with your new password ", { header: 'Change Password Failed' });
}else if ((password == current_password) && (new_password == retype_password)){
var formData = jQuery(this).serialize();
$.ajax({
type: "POST",
url: "update_password.php",
data: formData,
success: function(html){
$.jGrowl("Your password is successfully change", { header: 'Change Password Success' });
var delay = 2000;
setTimeout(function(){ window.location = 'dashboard_teacher.php' }, delay);
}
});
}
});
});
</script>
This is my update_password.php
<?php
include('dbcon.php');
include('session.php');
$new_password = $_POST['new_password'];
mysql_query("update admins set password = '$new_password' where admins_id = '$session_id'")or die(mysql_error());
?>
This is my login.php
$query = "select * from admins where username = '$usernameVal';";
$resultSet = mysqli_query($conn,$query);
if(#mysqli_num_rows($resultSet) > 0){
//check noraml user salt and pass
//echo "noraml";
$saltQuery = "select salt from admins where username = '$usernameVal';";
$result = mysqli_query($conn,$saltQuery);
$row = mysqli_fetch_assoc($result);
$salt = $row['salt'];
$saltedPW = $escapedPW . $salt;
$hashedPW = hash('sha256', $saltedPW);
$query = "select * from admins where username = '$usernameVal'
and password = '$hashedPW' ";
$resultSet = mysqli_query($conn,$query);
if(#mysqli_num_rows($resultSet) > 0){
$row = mysqli_fetch_assoc($resultSet);
echo "your username and password is correct";
session_start();
$_SESSION["id"]=$row["admins_id"];
header("location:group/dashboard_teacher.php");
}
else
{
echo "your username or password is incorrect";
}
}
}
?>
I want make protection on form, if user after using form want send another message in less than a minute he should get refuse. Other way every thing should pass.
For now I got something like this on view:
<!-- If Success form message send display this -->
<?php if (isset($_GET['msgSuccessSent']) == 1) { ?>
<h1 class="page-title text-center">Dziękujemy za wysłanie wiadomości</h1>
<div class="text-center">
Wyślij kolejną wiadomość
</div>
<?php } else { ?>
<?php if (isset($_GET['msgTimerError']) == 1) { ?>
<div id="errorMessage" class="alert alert-danger" role="alert">Przed wysłaniem kolejnej wiadomości musisz odczekać conajmniej minutę.</div>
<?php } ?>
<!-- If message isn't sent display form -->
<h1 class="page-title text-center">Formularz kontaktowy</h1>
<!-- Contact form -->
<form action="contact_send.php" method="post">
<!-- First name input -->
<div class="form-group">
<label for="firstName">Imię</label>
<input type="text" class="form-control" id="firstName" name="firstName" placeholder="Wpisz swoje imię">
</div>
<!-- Second name input -->
<div class="form-group">
<label for="secondName">Nazwisko</label>
<input type="text" class="form-control" id="secondName" name="secondName" placeholder="Wpisz swoje nazwisko">
</div>
<!-- Phone number input -->
<div class="form-group">
<label for="phoneNumber">Telefon kontaktowy</label>
<input type="tel" class="form-control" id="phoneNumber" name="phoneNumber" placeholder="Wpisz swój numer telefonu">
</div>
<!-- Email address input -->
<div class="form-group">
<label for="email">Adres e-mail</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Wpisz swój adres e-mail">
</div>
<!-- Message textarea -->
<div class="form-group">
<label for="message">Treść wiadomości</label>
<textarea type="text" class="form-control" id="message" name="message" rows="3"></textarea>
</div>
<!-- Send message button -->
<button type="reset" class="btn btn-default">Wyczyść formularz</button>
<button type="submit" class="btn btn-default pull-right">Wyślij</button>
</form>
<!-- Contact form end -->
<!-- End of If message isn't sent display form -->
<?php } ?>
And this is my contact_send.php file:
<?php
// Uncomment if you want to use session to check last form send
session_start();
$_SESSION['time'] = date('H:i:s');
header('Content-type: text/plain; charset=utf-8');
# Database connection settings
$dbHost = 'localhost'; // database hostname
$dbName = 'contactForm'; // database name
$dbUser = 'root'; // database user name
$dbPswd = ''; // database password
// Set connection
$connectionDb = new mysqli($dbHost, $dbUser, $dbPswd, $dbName);
// Check connection
if ($connectionDb->connect_error) {
die("Connection failed: " . $connectionDb->connect_error);
}
mysqli_set_charset( $connectionDb, 'utf8'); // change charset for mysqli to utf8
# Require ContactSend and DatabaseQuery class
require 'contact.class.php';
# Get ContactSend class
$sendEmail = new ContactSend();
$ipAddress = $_SERVER['REMOTE_ADDR']; // get user ip address
$currentDate = date('Y-m-d H:i:s'); // get Date time when user send form
# ***
# Here I check if time of last form send is greater than minute
# ***
$sqlCheck = "SELECT * FROM contactForm WHERE ipAddress = '$_SERVER[REMOTE_ADDR]' AND dateSend > DATE_SUB(NOW(),INTERVAL 1 MINUTE)";
if ($connectionDb->query($sqlCheck) === TRUE) {
$sendEmail->redirectToForm('form.php?msgTimerError=1');
} else {
// insert form values into database
$sqlQueryInsert =
"INSERT INTO contactForm (
firstName,
secondName,
phoneNumber,
email,
message,
dateSend,
ipAddress)
VALUES (
'$_POST[firstName]',
'$_POST[secondName]',
'$_POST[phoneNumber]',
'$_POST[email]',
'$_POST[message]',
'$currentDate',
'$ipAddress'
)";
// if data was save send mail and redirect to form
if ($connectionDb->query($sqlQueryInsert) === TRUE) {
# Get Parametrs from form
$sendEmail->sendTo = "kuchar.rafal#gmail.com"; // here insert your email address that you want get mails
$sendEmail->subject = "Tytuł wiadomości"; // here insert Subject of email
$sendEmail->firstName = $_POST['firstName']; // get user first name
$sendEmail->secondName = $_POST['secondName']; // get user second name
$sendEmail->phoneNumber = $_POST['phoneNumber']; // get user phone number
$sendEmail->email = $_POST['email']; // get user email address
// make mail content and insert form values into it
$sendEmail->message = "
Imię: " . $_POST['firstName'] . "
Nazwisko: " . $_POST['secondName'] . "
Numer telefonu: " . $_POST['phoneNumber'] . "
Adres email: " . $_POST['email'] . "
Wiadomość: " . $_POST['message'];
$sendEmail->mailSender(); // send mail
} else {
echo "Error: " . $sqlQueryInsert . "<br>" . $connectionDb->error; // display error if database connection or query has error
}
// close connection to database
$connectionDb->close();
// redirect to form
$sendEmail->redirectToForm('form.php?msgSuccessSent=1');
}
?>
$msgTimerError should display if in database exist row with user IP and date of create is less than minute other ways it should just display form.
$sqlCheck is for check in database if time of last form send is greater than minute if its not it redirect user to form.php with msgTimerError=1 with method get, otherwise it will add new form values to database and send mail.
Ok i changed line in contact_send.php so it works... (im so ashamed...)
# Check if user send form less than minute, if true return to form with error
$sqlCheck = "SELECT * FROM contactForm WHERE ipAddress = '$ipAddress' AND dateSend > DATE_SUB(NOW(),INTERVAL 1 MINUTE) LIMIT 1";
$result = $connectionDb->query($sqlCheck);
if (mysqli_fetch_row($result)) {
$sendEmail->redirectToForm('form.php?msgTimerError=1'); // return to form page
} else {
Heres is all relevant code. What I want to do is sent some parameters to a php file using ajax, and check if they are in db. If not echo and error message and if they are echo success message. I don't know how to retrieve all result from the database and compare them with the ones I input. Thank you.
AJAX
$( document ).ready(function() {
$("input[name=send_login]").click(function() {
var value_email_login = $("#email_login").val() ;
var value_password_login = $("#password_login").val() ;
if(value_email_login == '' && value_password_login == ''){
$(".info_message_login").show();
$(".info_message_login").html("Campos Vacios");
}else{
$.ajax({
type: 'POST',
url: 'php/login.php',
data: {email: value_email_login, password: value_password_login},
success: function(){
$(".info_message_login").show();
$(".info_message_login").text("Bienvenido...");
},
error: function(response){
$(".info_message_login").show();
$(".info_message_login").text(response.responseText);
},
});
}
});
});
FORM
<form class="" action="" method="post">
<div class="form-group">
<input class="form-control" type="text" name="email" id="email_login" placeholder="Email"/>
</div>
<div class="form-group">
<input class="form-control" type="password" name="password" id="password_login" placeholder="Password"/>
</div>
<div class="form-group">
<input class=" btn btn-default " type="button" name="send_login" value="Send"/>
</div>
<div class="form-group">
<input class=" btn btn-default " type="reset" name="reset_login" value="Reset"/>
</div>
<div class="info_message_login" style="display:none;">
</div>
</form>
PHP FILE
<?php
session_start();
require_once "db.php";
$email = trim($_POST['email']);
$password = trim($_POST['password']);
$sql_login = 'SELECT * FROM users WHERE email = :email AND password = :password';
$statement = $connection->prepare($sql_login);
$statement->bindValue(':email', $email);
$statement->bindValue(':password', $password);
$statement->execute()
$statement = $connection->prepare(<<<SQL
SELECT *
FROM users
WHERE email = :email
AND password = :password
SQL
);
$statement->execute(array(":email" => $email,
":password" => $password));
if($statement->fetch()) {
$_SESSION['login'] = 'ok';
}
I let you hash passwords with sha1 or whatever you want
I have a login form built into a site that uses PHP and JQuery to validate. However, I would like to add a function built into the PHP or the JQuery validator that will take the user_id of the user logged in and compare it to another table in the same database. The other table will have data that will allow users to select from a drop-down list of projects specific to that user that will ultimately control what the user sees in the website. The 2 tables are the "login" table and "projects" table. I think I need to fetch the user_id from the login table and compare to the user_id on the projects table to see if it matches. Not sure how to go about that.
PHP:
<?php
session_start();
$con = mysqli_connect("localhost","****","****","db") or die("Connection error: " . mysqli_error($con));
$query = mysqli_query("projects");
if(isset($_POST['submit'])){
$username = $_POST['user_name'];
$password = $_POST['pwd'];
$stmt = $con->prepare("SELECT * FROM login WHERE username = ? AND password = ? LIMIT 1");
$stmt->bind_param('ss', $username, $password);
$stmt->execute();
$stmt->bind_result($username, $password);
$stmt->store_result();
if($stmt->num_rows == 1)
{
while($stmt->fetch())
{
$_SESSION['Logged'] = 1;
$_SESSION['user_name'] = $username;
$_SESSION['timeout'] = time();
echo 'true';
}
}
else {
echo 'false';
}
$stmt->close();
}
else{
}
$con->close();
?>
JQuery:
$("#login_validation").click(function(){
var username=$('#user_name').val();
var password=$('#password').val();
if(username===''){
$("#add_err").html("*Please enter a user name.");
return false;
}
else if(password===''){
$("#add_err").html("*Please enter a password.");
return false;
}
else{
var loadTimeout = setTimeout(tick, 12100);
$.ajax({
type: "POST",
timeout:12000,
url: "login_validation.php",
data: "submit=true&user_name="+username+"&pwd="+password,
beforeSend:function(){
$("#add_err").fadeIn("fast").html('<img src="image/loader.gif" />');
},
success: function(html){
clearTimeout(loadTimeout);
var html=trim(html);
if(html=='true'){
$("#login_b").fadeOut("normal");
$("#login_b").promise().done(function(){
$('#projects').css("display", "block");
})
//$('#profile').css("display", "block");
//$("#profile").html("<a href='logout_session.php' id='logout'>Logout</a>");
}
else{
$("#add_err").html("*Wrong username or password");
}
}
});//end ajax
return false;
}
});//end #login_validation
$("#project_validation").click(function(){
});
var tick = function(){
$("#add_err").html('Unable to fetch page!');
}
function trim(str){
var str=str.replace(/^\s+|\s+$/,'');
return str;
}
Form:
<fieldset id="login_form_wrap" class="login_form_header">
<legend>CUSTOMER LOGIN</legend>
<?php session_start(); ?>
<div id="profile">
<?php if((!isset($_SESSION['user_name'])) || ($_SESSION['timeout'] + 10 * 60 < time())){ ?>
<div id="login_a">
<a id="login_profile" href="#">click to login</a>
</div>
<?php }else {;?>
<a href='logout_session.php' id='logout'>Logout</a>
<!-- header('location: dashboard.php'); -->
<?php } ?>
</div>
<form action="login_validation.php" id="login_form" method="POST">
<div id="login_b">
<div class="welcome"></div>
<div class="wrapper">
<span class="col1">USER NAME:</span>
<input type="text" id="user_name" name="user_name" class="input" required />
</div>
<div class="wrapper">
<span class="col1">PASSWORD:</span>
<input type="password" id="password" name="password" class="input" required />
</div>
<div class="wrapper">
<span class="col1"></span>
<input type="submit" name"submit" id="login_validation" value="SUBMIT" />
<input type="reset" id="cancel_hide" value="CANCEL" />
<div class="err" id="add_err"><br></div>
<div id="divMayus" style="visibility:hidden">Caps Lock is on.</div>
</div>
</div>
<div id="projects">
<div class="welcome">Welcome <?php echo $_SESSION['user_name']; ?></div>
<div class="wrapper">
<span class="col1">PROJECTS:</span>
<select id="Projects" class="input">
<option value="" selected="selected" disabled='disabled'>Choose a Project...</option>
<?php
// Loop through the query results, outputing the options one by one
while ($row = mysql_fetch_array($query)) {
echo '<option value="'.$row['projects'].'">'.$row['projects'].'</option>';
}?>
</select>
</div>
<div class="wrapper">
<span class="col1"></span>
<input type="submit" name"submit" id="project_validation" value="SELECT" />
<div class="err" id="add_err"><br></div>
</div>
</div>
</form>
I'm still learning JQuery and PHP so any help in the right direction is greatly appreciated.
grab the users id you are checking
run a query for of the table, where the user id's allowed are, and explode that into an array
then check to see if the user id you're checking is within that array.