Checking if Username and Password is match or available - Jquery - javascript

I'm having a problem on my code which the username and password does not match.
Here is my output. When the username and password is not match, then it will give a message that it is not match , However, when the username and password match, then there will be a message that it is match here is my code below:
html code
<body>
<div class="container box">
<div class="form-group">
<h3 align="center">Live Username Available or not By using PHP Ajax Jquery</h3><br />
<label>Enter Username</label>
<input type="text" name="username" id="username" class="form-control" />
<input type="password" name="password" id="password" class="form-control" />
<span id="availability"></span>
<br /><br />
<button type="button" name="register" class="btn btn-info" id="register" disabled>Register</button>
<br />
</div>
<br />
<br />
</div>
</body>
</html>
script code
<script>
$(document).ready(function(){
$('#username','#password').blur(function(){
var username = $(this).val();
var password = $(this).val();
$.ajax({
url:'check.php',
method:"POST",
data:{user_name:username, password:password},
success:function(data)
{
if(data != '1')
{
$('#availability').html('<span class="text-danger">Username and Password not Match</span>');
$('#register').attr("disabled", true);
}
else
{
$('#availability').html('<span class="text-success">Username and Password Available</span>');
$('#register').attr("disabled", false);
}
}
})
});
});
</script>
check.php - my database connection and query that fetch it from the database
<?php
//check.php
$connect = mysqli_connect("localhost", "username", "", "dbname");
if(isset($_POST["user_name"] && $_POST["password"]))
{
$username = mysqli_real_escape_string($connect, $_POST["user_name"]);
$password = mysqli_real_escape_string($connect, $_POST["password"]);
$query = "SELECT * FROM admin WHERE username = '".$username."' AND password = '".$password."' ";
$result = mysqli_query($connect, $query);
echo mysqli_num_rows($result);
}
?>

Notes
You are wide open to SQL injection. You should be using prepared statements instead. Please read How can I prevent SQL injection in PHP?
You should not store passwords in plain text. Instead, use PHP's password_hash and password_verify functions to hash and verify.
Answer
You are using isset incorrectly. To check that multiple values are set, separate them by commas, not with &&:
if(isset($_POST["user_name"], $_POST["password"]))
Your PHP code as it currently stands won't produce any output as it will terminate with a fatal error on that line.
In your jQuery, you're not specifying multiple selectors correctly. They should all be inside the same set of quotes:
$('#username, #password').blur(function(){
You also need to change this code, which will set both username and password values to the same thing:
var username = $(this).val();
var password = $(this).val();
to
var username = $('#username').val();
var password = $('#password').val();

Related

Ajax Form Not Doing Anything

I have a form using Ajax that is suppose to show an error to the user when something is incorrect when the login. When I click the submit button nothing happens. I hate asking Stack overflow but you got to do what you got to do. And yes, I have Apache configured to not need file extensions.
This is the tutorial I am following: https://www.youtube.com/watch?v=L7Sn-f36TGM
Login Script:
require("dbh.php");
if(isset($_POST['submit'])) {
$email = $_POST['email'];
$pwd = $_POST['pwd'];
$errorEmpty = false;
$errorEmail = false;
$errorWrong = false;
if(empty($email) || empty($pwd)) {
echo "<p class='loginText'>Please Enter an Email Address and Password!</p>";
$errorEmpty = true;
} else if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "<p class='loginText'>Please Enter a Valid Email Address!</p>";
$errorEmail = true;
} else {
echo "Success!";
}
} else {
echo "<p class='loginText'>An Error Occurred!</p>"
}
header("/login?test");
loginForm.js
$(document).ready(function() {
$("#loginFormInput").submit(function(event) {
event.preventDefault();
var email = $("#emailLogin").val();
var pwd = $("#pwdLogin").val();
$(".errorText").load("../php-scripts/login", {
email: email,
pwd: pwd
});
});
});
HTML Form:
<p class="errorText"></p>
<form action="../php-scripts/login.php" method="post" id="loginFormInput">
<input type="text" name="email" class="textInput" id="emailLogin" placeholder="Email" maxlength="512"> <br>
<input type="password" name="pwd" class="textInput" id="pwdLogin" placeholder="Password" maxlength="1024"> <br>
<p class="rememberText">Remember Me:</p>
<input type="checkbox" name="remember" class="rememberBox"> <br>
<input type="submit" value="Login" name="submit" class="submitInput" title="Login">
</form>
Your PHP code is doing if (isset($_POST['submit'])), but when you do the AJAX submission you don't provide a submit parameter. You need to add that to the parameters:
$(".errorText").load("../php-scripts/login", {
email: email,
pwd: pwd,
submit: 'Login'
});
Or you could remove that check from the PHP, if that script is only used to process the AJAX requests.
I think you're missing an element with class name errorText
Try adding a <div class="errorText"></div> somewhere

Insert data into MySQL database from Javascript calling PHP file

I have the below code which calls a .php file to insert data into a MySQL database, but cant seem to get the .php file to run. Any suggestions?
I am very new to script so i am trying this registration form example. The database, 'college', with its table, 'registration', seems to be fine, but no php code executes. It must be something really simple but i cant seem to work it out?
$(document).ready(function() {
$("#register").click(function() {
var name = $("#name").val();
var email = $("#email").val();
var password = $("#password").val();
var cpassword = $("#cpassword").val();
if (name == '' || email == '' || password == '' || cpassword == '') {
alert("Please fill all fields...!!!!!!");
} else if ((password.length) < 8) {
alert("Password should atleast 8 character in length...!!!!!!");
} else if (!(password).match(cpassword)) {
alert("Your passwords don't match. Try again?");
} else {
//alert(name); //This line reads fine
$.post("register.php",
{
name1: name,
email1: email,
password1: password
},
function(data) {
if (data == 'You have Successfully Registered.....') {
$("form")[0].reset();
}
alert(data);
});
}
});
});
<?php
$connection = mysql_connect("localhost", "root", "Winchester12"); // Establishing connection with server..
$db = mysql_select_db("college", $connection); // Selecting Database.
$name=$_POST['name1']; // Fetching Values from URL.
$email=$_POST['email1'];
echo $email;
$password= sha1($_POST['password1']); // Password Encryption, If you like you can also leave sha1.
// Check if e-mail address syntax is valid or not
$email = filter_var($email, FILTER_SANITIZE_EMAIL); // Sanitizing email(Remove unexpected symbol like <,>,?,#,!, etc.)
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
echo "Invalid Email.......";
}else{
$result = mysql_query("SELECT * FROM registration WHERE email='$email'");
$data = mysql_num_rows($result);
if(($data)==0){
$query = mysql_query("insert into registration(name, email, password) values ('$name', '$email', '$password')"); // Insert query
if($query){
echo "You have Successfully Registered.....";
}else
{
echo "Error....!!";
}
}else{
echo "This email is already registered, Please try another email...";
}
}
mysql_close ($connection);
?>
<!DOCTYPE html>
<html>
<head>
<title>Squash Registration Form</title>
<meta name="robots" content="noindex, nofollow">
<!-- Include CSS File Here -->
<link rel="stylesheet" href="style.css"/>
<!-- Include JS File Here -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="registration.js"></script>
</head>
<body>
<div class="container">
<div class="main">
<form class="form" method="post" action="#">
<h2>Squash Registration Form</h2>
<label>Name :</label>
<input type="text" name="dname" id="name">
<label>Email :</label>
<input type="text" name="demail" id="email">
<label>Password :</label>
<input type="password" name="password" id="password">
<label>Confirm Password :</label>
<input type="password" name="cpassword" id="cpassword">
<input type="button" name="register" id="register" value="Register">
</form>
</div>
</body>
</html>
It could be a path related issue.
you might want to review the path to the register.php file to be sure its in the right place.
It seems that nothing is passed to register.php file. Please try with 'ajax' instead of jquery post.

window.location.href don't work with AJAX

For some reason, the "window.location.href" function does not work for me, can't seem to find out why.
This is the code from index.php:
<div class="dropdown-menu">
<div style="width: 300px;">
<div class="panel panel-primary">
<div class="panel-heading">Login</div>
<div class="panel-heading">
<label for="email">Email</label>
<input class="form-control" id="email" name="email" required />
<label for="password">Password</label>
<input type="password" class="form-control" id="password" name="password" required />
<p><br/></p>
Forgotten Password<input type="button" class="btn btn-success" name="login" id="login" value="Login">
</div>
</div>
<div class="panel-footer"></div>
</div>
</div>
And this is the function in the "action.php" file that is mentioned in the jQuery function:
<?php
if(isset($_POST["userLogin"])){
$email = mysqli_real_escape_string($con, $_POST["userEmail"]);
$password = md5($_POST["userPassword"]);
$sql = "SELECT * FROM user_info WHERE email = '$email' AND password = '$password'";
$run_query = mysqli_query($con, $sql);
if($run_query===false){
echo mysqli_error($con);
} else {
$row = mysqli_fetch_array($run_query);
$_SESSION["uid"]= $row["user_id"];
$_SESSION["name"]= $row["first_name"];
echo "welcome";
}
}
?>
This is the jQuery with the AJAX function:
$(document).ready(function(){
$("#login").click(function(event){
event.preventDefault();
var email = $("#email").val();
var pass = $("#password").val();
$.ajax({
url : "action.php",
method : "POST",
data : {userLogin: 1, userEmail:email, userPassword:pass},
success : function(data){
if(data == "welcome"){
window.location.href = "profile.php";
}
/* alert(data);*/
}
});
});
});
notes:
As you can see in the jQuery function, there is this: "alert(data);". I wanted to look if it does work and put it on the screen without the "window.location.href" function to see that the "if" statement is correct, and it does work. Further more, when I go directly to the profile.php file, I see That the user is logged in, which means for me that the SQL functions is working fine, just it will not Re-Direct me to that (profile.php) page.
window.location.href expects an absolute url or a url relative to your domain (if it starts with a /).
If you only want to change the file part of your current path, you can use window.location.assign("profile.php")
If you want to redirect inside same domain
window.location.href = "/profile.php";
If you want to redirect to another domain
window.location.href = "http://www.antotherdomainname.com/profile.php";

issue with ajax login script

I'm very new to ajax, and I'm trying to make a login script that doesn't require a page reload - it's working well except I attempt to set a session variable on the processing page, but no session variable is set.
My form:
<div class="form-bottom">
<form role="form" class="login-form">
<div class="form-group">
<label class="sr-only" for="username">Username</label>
<input type="text" name="username" placeholder="Username..." class="form-username form-control" id="username">
</div>
<div class="form-group">
<label class="sr-only" for="password">Password</label>
<input type="password" name="password" placeholder="Password..." class="form-password form-control" id="password">
</div>
<input type="submit" id="submit" class="btn" style="width:100%;background-color:lightblue;" value="Log In" id="login"/>
</form>
<? echo $_SESSION['Name']; ?>
</div>
My ajax:
<script type="text/javascript" >
$(function() {
$("#submit").click(function() {
var username = $("#username").val();
var password = $("#password").val();
var dataString = 'username='+ username + '&password=' + password;
if(username=='' || password=='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "ajax/login.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
window.setTimeout(function () {
location.href = "index.php";
}, 3000);
}
});
}
return false;
});
});
</script>
My php script:
include('./static/config.php');
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if(isset($_POST)) {
$username = mysqli_real_escape_string($con, $_POST['username']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$sql = "SELECT Name FROM techs WHERE Username='$username' AND Password='$password'";
$result = mysqli_query($con, $sql);
$exists = mysqli_num_rows($result);
if($exists == 1) {
$row = mysqli_fetch_assoc($result);
$_SESSION['Name'] = $row['Name'];
}
}
I was able to get it working the way I wanted it to.
Form:
<div id="box">
<div class="row">
<div class="col-sm-6 col-sm-offset-3 form-box">
<div class="form-top">
<div class="form-top-left">
<h3>Log-in</h3>
<span id="error" class="error"></span>
</div>
<div class="form-top-right">
<i class="fa fa-key"></i>
</div>
</div>
<div id="box" class="form-bottom">
<form class="login-form" action="" method="post">
<div class="form-group">
<label class="sr-only" for="username">Username</label>
<input type="text" name="username" placeholder="Username..." class="form-username form-control" id="username">
</div>
<div class="form-group">
<label class="sr-only" for="password">Password</label>
<input type="password" name="password" placeholder="Password..." class="form-password form-control" id="password">
</div>
<input type="submit" id="login" class="btn" style="width:100%;background-color:lightblue;" value="Log In" id="login"/>
</form>
</div>
</div>
</div>
</div>
AJAX Code:
<script src="js/jquery.min.js"></script>
<script src="js/jquery.ui.shake.js"></script>
<script>
$(document).ready(function() {
$('#login').click(function()
{
var username=$("#username").val();
var password=$("#password").val();
var dataString = 'username='+username+'&password='+password;
if($.trim(username).length>0 && $.trim(password).length>0)
{
$.ajax({
type: "POST",
url: "ajax/login.php",
data: dataString,
cache: false,
beforeSend: function(){ $("#login").val('Connecting...');},
success: function(data){
if(data)
{
window.setTimeout(function () {
location.href = "index.php";
}, 3000);
}
else
{
$('#box').shake();
$("#login").val('Login')
$("#error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
}
}
});
}
return false;
});
});
</script>
PHP (ajax/login.php):
<?php
include("../static/config.php");
session_start();
if(isSet($_POST['username']) && isSet($_POST['password']))
{
// username and password sent from Form
$username=mysqli_real_escape_string($con,$_POST['username']);
$password=mysqli_real_escape_string($con,$_POST['password']);
$result=mysqli_query($con,"SELECT Name FROM techs WHERE Username='$username' and Password='$password'");
$count=mysqli_num_rows($result);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1)
{
$_SESSION['Name']=$row['Name'];
echo $row['Name'];
}
}
?>
Since you've stated you're very new to Ajax, you start off pretty well.
There are however a couple of things to know how this works.
You want to avoid a page refresh, yet you don't print out any responses because you're not returning anything in the ajax request. You instead set a session variable which will show up at the next page request (so a refresh)
$.ajax({
type: 'POST',
url: 'ajax/login.php',
data: { username: $("#username").val(), password: $("#password").val() },
success: function (data) {
$('.form-bottom').html(data); // here we replace the form with output of the ajax/login.php response.
}
});
And for the PHP side of things:
$sql = "SELECT Name FROM techs WHERE Username='$username' AND Password='$password'";
if(($result = mysqli_query($con, $sql)) != false){ // always verify if your query ran successfully.
if(mysqli_num_rows($result)){ // or compare with == 1, but assuming a username is unique it can only be 1 so it equals to true.
echo mysqli_fetch_assoc($result)['name']; // index, columns, etc should always be lower cased to avoid confusion.
// Obviously you can store it in a session
// But for now just output the data so we can use it as our response.
// json is very usefull with sending large amounts of data.
}
}
The idea of Ajax is that you can request an update, but you need to update your page with javascript manually in order to make it work.
I think you forget to start the session.So start the session at the top of your script. Hope it will help.
session_start();
include('./static/config.php');
if(isset($_POST)) {
$username = mysqli_real_escape_string($con, $_POST['username']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$sql = "SELECT Name FROM techs WHERE Username='$username' AND Password='$password'";
$result = mysqli_query($con, $sql);
$exists = mysqli_num_rows($result);
if($exists == 1) {
$row = mysqli_fetch_assoc($result);
$_SESSION['Name'] = $row['Name'];
}
}
3 things you could try:
On the page where you are trying to set the session variable you would have to use proper php opening tags like <?php
Second thing is that you would have to put a value in your session like $_SESSION['hello'] = 'hello';
Third thing, on every page where you handle your session you would have to call <?php session_start(); ?> for it to work.
Goodluck!

Trying to Add record to mysql using php and html

I'm trying to add a record to an sql table, and I'm having trouble doing so.
I have a sign up page that will take in the username, password, and email of the user, and pass them to a small php script which calls functions from a larger php file.
When I try press the signup button, the page just refreshes, and nothing is added to the table.
Any advice is appreciated.
html:
<body>
<div class="body"></div>
<div class="grad"></div>
<div class="header">
</div>
<br>
<div class="signup">
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script type = "text/javascript" src="js/js_functions.js"></script>
<form method="post" action ="signup_script.php" onsubmit = "return checkEmailandPassword(this);" method = "post" >
<input type="text" placeholder="username" name="username" required = "required" maxlength = "15"><br>
<input type ="email" placeholder = "email" name = "email" required = "required" maxlength = "50"><br>
<input type ="email" placeholder = "re-enter email" name = "reemail" required = "required" maxlength = "50"><br>
<input type="password" placeholder="password" name="password" required = "required" pattern = "(?=.*\d)(?=.*[A-Z]).{10,}"><br>
<input type="password" placeholder="re-enter password"name="repassword" required = "required"><br>
<p class = "passwordreq">Password must:</p>
<ol class = "passwordreq">
<li>Have 10 characters</li>
<li>Have one number</li>
<li>Have one uppercase letter</li>
</ol>
<input type="submit" value="sign up"> <input type="button" value="go back" onclick="window.location='index.html'">
</form>
</body>
</html>
small php file:
include_once('profile_Functions.php');
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
createUser($username,$password,$email);
large php file:
<?php
extract($_GET);
extract($_POST);
extract($_SERVER);
function setup(){
extract($_GET);
extract($_POST);
extract($_SERVER);
$host="localhost";
$user="root";
$passwd="";
$connect=mysql_connect($host,$user,$passwd) or die("error connecting mysql server");
mysql_select_db('oddjob',$connect) or die("error accessing db");
}
function createUser($name, $pass, $email){
setup();
$hashed_password = password_hash($pass, PASSWORD_DEFAULT);
$sql = "insert into profiles (UserName, Password, Email) values ($name, $hashed_password, $email); ";
$res = mysql_query($sql);
} ?>
Your insert statement fails. You should surround character values inside the values part with quotes:
$sql = "insert into profiles (UserName, Password, Email)
values ('$name', '$hashed_password', '$email'); ";
It would be good to actually check that $res is not false after the execution of mysql_query.
Note that it is unsafe to inject user input values directly into SQL statements. Read about SQL injection attacks and how you can protect your database from them.

Categories

Resources