if statement not working inside ajax - php

I'm trying to redirect a user after he presses a sign-in button. So it happens, and the if condition is not met, and the data itself is correct with no extra characters and contains a single one "A". for some reason it won't work.
I have tried to use the trim() function but to no avail.
Here is my code:
$("#login").click(function(event){
event.preventDefault();
var email = $("#email").val();
var pass = $("#password").val();
$.ajax({
url: "login.php",
method: "POST",
data: {userLogin: 1, userEmail:email, userPassword:pass},
success: function(data){
if(data!= "A"){
alert(data);
}else{
window.location.href="profile.php";
}
}
})
})
And this is the PHP:
<?php
include 'connection/connect.php';
session_start();
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);
$count = mysqli_num_rows($run_query);
if($run_query===false){
echo mysqli_error($con);
}
elseif ($count == 1){
$row = mysqli_fetch_array($run_query);
$_SESSION["uid"] = $row["user_id"];
$_SESSION["name"] = $row["first_name"];
echo trim("A");
}
}
?>
And the HTML:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<li>SignIn
<ul 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 type="email" 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="submit" class="btn btn-success" id="login" value="Login">
</div>
<div class="panel-footer" id="e_msg"></div>
</div>
</div>
</ul>
</li>
</body>
</html>
furthermore, when i go directly to the page "profile.php", the user is logged in. That means that the data is passed correctly.
What can be the problem? Thanks.
Edit, the alert prints "A".

try javascript trim() method to compare string.
if(data.trim()=="A"){
window.location.href="profile.php";
}else{
alert(data);
}

Related

What's wrong with my AJAX and PHP whern I call it to login?

I have some trouble with my login form using ajax and php, could somebody con solve this??
This is code html:
login.html
<div id="id01" class="modal">
<form class="modal-content animate" action="" method="POST" id="login-form">
<div class="container">
<label for="login-email"><b>Username</b></label>
<input type="text" placeholder="Enter Email" id="login-email" name="login-email" required>
<label for="login-password"><b>Password</b></label>
<input type="password" placeholder="Enter Password" id="login-password" name="login-password" required>
<label>
<input type="checkbox" checked="checked" name="remember"> Remember me
</label><br>
<span id="showError"></span>
<button type="submit" id="btn-login" name="btn-login">Login</button>
</div>
<div class="container" style="background-color:#f1f1f1">
<button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancel-btn">Cancel</button>
<span class="psw">Forgot password?</span>
</div>
</form>
</div>
<script>
$(document).ready(function(){
$("#btn-submit").click(function{
var login-email = $("#login-email").val();
var login-password = $("#login-password").val();
var error = $("#showError");
if(login-email != "" && login-password != ""){
$.ajax({
url: "checkLogin.php",
type: "POST",
data: { login-email: login-email, login-password: login-password},
success: function(response){
var msg = "";
if(response == "success"){
window.location = 'profile.php';
} else {
msg = "Tên đăng nhập hoặc mật khẩu không chính xác.";
}
$('#id01').css({"display": "block"});
error.html(msg);
}
});
} else {
error.html("Email đăng nhập hoặc mật khẩu không được bỏ trống.");
return false;
}
});
});
</script>
and this is code php
login.php
if(isset($_POST["btn-login"])){
$email = trim($_POST["login-email"]);
$password = trim($_POST["login-password"]);
$sql_login = "SELECT email, password, permission FROM users where email='$email' and password='$password'";
$db->query($sql_login);
$rows = $db->findOne();
$permission = $rows['permission'];
if($rows['email'] == $email && $rows['password'] == $password){
echo "success";
} else {
echo "fail";
}
exit();
}
It seem to be not to load into ajax and php code cause i've try so many time but i didn't know the bugs in here.
you call checkLogin.php but the code php is in login.php
In the login.php code, you check the btn-login but the post data from client have no btn-login
{ login-email: login-email, login-password: login-password}
so the if block will never work.
if(isset($_POST["btn-login"])){
...
}
you can change like this
if(isset($_POST["login-email"]) && isset($_POST["login-password"])){
...
}
It appears at first glance that your jQuery is referencing btn-submit but your html defines this as btn-login instead.

How to stay on same page after login

I am building an event registration system which displays event registration list if the user is logged in without page refresh using Ajax. However, when I try to login I get undefined index name on line echo "Hello ".$_SESSION["name"]."<br/>"; in index.php. My code is:-
index.php:-
<?php
ob_start();
session_start();
require_once('dbconnect.php');
require_once('function.php');
?>
<!DOCTYPE html>
<html>
<head>
<title>Login Registration</title>
<link href="style.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="crossorigin="anonymous"></script>
<script src="script.js"></script>
</head>
<body>
<div id="wrapper">
<!--Login div-->
<div id="logincontainer">
<form id="loginform" method="post">
<h3>Login</h3>
<div class="display-error" style="display: none;"></div>
<input type="email" name="lemail" placeholder="Enter email address" required>
<input type="password" name="lpassword" placeholder="Enter password" required>
<input type="submit" value="Sign In">
<p>Forgot Password</p>
<p id="bottom">Don't have an account yet? Sign up</p>
</form>
</div>
<div id="signupcontainer">
<form id="registerform" method="post">
<h3>Register</h3>
<div class="display-error" style="display: none;"></div>
<input type="text" name="rname" placeholder="Full Name" required>
<input type="email" name="remail" placeholder="Enter valid email" required>
<input type="password" name="rpassword" placeholder="Password" required>
<input type="text" name="rmobile" maxlength="10" pattern="[0-9]{10}" placeholder="Mobile" required>
<input type="submit" value="Create Account">
<p id="bottom">Already have an account? Sign In</p>
</form>
</div>
<!--Testing refresh portion-->
<div id="after-login" style="display: none;">
<?php
echo "Hello ".$_SESSION["name"]."<br/>";
echo '<span class="glyphicon glyphicon-logout"></span>Sign Out<br/>';
?>
<form id="events" method="post">
Code Ardor<input type="checkbox" name="coding[]" value="ardor">
Designophy<input type="checkbox" name="coding[]" value="design"><br>
<input type="submit" value="Submit" name="submit-btn">
</form>
</div>
<!--Testing portion ends-->
</div>
<script>
$(document).ready(function(){
$("#loginform").submit(function(){
var data = $("#loginform").serialize();
checkRecords(data);
return false;
});
function checkRecords(data){
$.ajax({
url : 'loginprocess.php',
data : data,
type : 'POST',
dataType : 'json',
success: function(data){
if(data.code == 200){
//alert('You have successfully logged in');
//window.location='dashboard.php';
$("#logincontainer").hide();
$("#after-login").show();
}
else{
$(".display-error").html("<ul>"+data.msg+"</ul");
$(".display-error").css("display","block");
}
},
error: function(){
alert("Email/Password is Incorrect");
}
});
}
});
</script>
<!--Signup Ajax-->
<script>
$(document).ready(function(){
$("#registerform").submit(function(){
var data = $("#registerform").serialize();
signupRecords(data);
return false;
});
function signupRecords(data){
$.ajax({
url : 'signupprocess.php',
data : data,
type : 'POST',
dataType : 'json',
success: function(data){
if(data.code == 200){
alert('You have successfully Signed Up \n Please Login now.');
setTimeout(function(){
location.reload();
},500);
}
else{
$(".display-error").html("<ul>"+data.msg+"</ul");
$(".display-error").css("display","block");
}
},
error: function(jqXHR,exception){
console.log(jqXHR);
}
});
}
});
</script>
</body>
loginprocess.php
<?php
ob_start();
session_start();
require_once('dbconnect.php');
require_once('function.php');
$errorMsg = "";
$email = trim($_POST["lemail"]);
$password = trim($_POST["lpassword"]);
if(empty($email)){
$errorMsg .= "<li>Email is required</li>";
}
else{
$email = filterEmail($email);
if($email == FALSE){
$errorMsg .= "<li>Invalid Email Format</li>";
}
}
if(empty($password)){
$errorMsg .= "<li>Password Required.</li>";
}
else{
$password = $password;
}
if(empty($errorMsg)){
$query = $db->prepare("SELECT password from users WHERE email = ?");
$query->execute(array($email));
$pwd = $query->fetchColumn();
if(password_verify($password, $pwd)){
$_SESSION['email'] = $email;
//Testing piece
$qry = $db->prepare("SELECT name from users WHERE email = ?");
$qry->execute(array($email));
$nme = $qry->fetchColumn();
$_SESSION['name']=$nme;
//Testing code ends
echo json_encode(['code'=>200, 'email'=>$_SESSION['email']]);
exit;
}
else{
json_encode(['code'=>400, 'msg'=>'Invalid Email/Password']);
exit;
}
}
else{
echo json_encode(['code'=>404, 'msg'=>$errorMsg]);
}
?>
As far as I can see the problem is that after login call you DO NOT reload the #after-login container contents - you only show it.
if(data.code == 200){
//alert('You have successfully logged in');
//window.location='dashboard.php';
$("#logincontainer").hide();
$("#after-login").show();
}
In the other words the #after-login contents only load on the first page load (before login) and then are not updated by your ajax call (only then you would have access to $_SESSION["name"]).
IMHO proper solution would be to return the $_SESSION["name"] value in the loginprocess.php response and update it in the #after-login container before showing it (eg. use an empty span where the name should appear which you'll fill out on login).
//Something like
if(data.code == 200){
//alert('You have successfully logged in');
//window.location='dashboard.php';
$("span#name_placeholder").text(data.name) //return name from loginprocess.php
$("#logincontainer").hide();
$("#after-login").show();
}
The best solution would to be to create a html element like this for the
<div id="after-login" style="display: none;">
<h5 id="Username"></h5>
<?php
echo '<span class="glyphicon glyphicon-logout"></span>Sign Out<br/>';
?>
<form id="events" method="post">
Code Ardor<input type="checkbox" name="coding[]" value="ardor">
Designophy<input type="checkbox" name="coding[]" value="design"><br>
<input type="submit" value="Submit" name="submit-btn">
</form>
</div>
then after this include the username in the json like this
$qry = $db->prepare("SELECT name from users WHERE email = ?");
$qry->execute(array($email));
$nme = $qry->fetchColumn();
//$_SESSION['name']=$nme;
//Testing code ends
echo json_encode(['code'=>200, 'email'=>$_SESSION['email'],'username'=>$nme]);
exit;
on the ajax call you can now access the json response with the username included and feed the span element with the username like this
if(data.code == 200){
//alert('You have successfully logged in');
//window.location='dashboard.php';
$("#username").test(data.username);
$("#logincontainer").hide();
$("#after-login").show();
}

Can someone make an example of how to check if email and password exists in database with PDO? (FOR DUMMIES).

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

After php user validation look up user_id to give user certain access

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.

JQuery login does not respond

I'm new to Jquery, and I'm trying to create a login page, using JQuery and PHP but it doesn't respond when I click the login button, what I want is that after the login is success it redirect to index.html.
here is the JQuery code :
<script type="text/javascript" >
$(document).ready(function() {
$("form#memberlogin").submit(function(e) {
dataString = $(this).serialize();
$.post("check_login.php", dataString, function(data) {
$('form#memberlogin').hide();
window.location="index.html"
});
e.preventDefault();
});
});
</script>
Here is my form code :
<form id="memberlogin" class="form-horizontal" method="post">
<fieldset>
<div class="input-prepend" title="Username" data-rel="tooltip">
<span class="add-on"><i class="icon-user"></i></span><input id="username" autofocus class="input-large span10" name="username" id="username" type="text" value="admin" />
</div>
<div class="clearfix"></div>
<div class="input-prepend" title="Password" data-rel="tooltip">
<span class="add-on"><i class="icon-lock"></i></span><input id="password" class="input-large span10" name="password" id="password" type="password" value="admin123456" />
</div>
<div class="clearfix"></div>
<div class="input-prepend">
<label class="remember" for="remember"><input type="checkbox" id="remember" />Remember me</label>
</div>
<div class="clearfix"></div>
<p class="center span5">
<button type="submit" class="btn btn-primary">Login</button>
</p>
</fieldset>
</form>
And this is my php code :
<?php
ob_start();
$con=mysql_connect(localhost,"root","-----");
if(!con)
{
die(mysql_error());
exit();
}
mysql_select_db("sure") or die(mysql_error());
$user=$_POST['username'];
$pass=$_POST['password'];
if(get_magic_quotes_gpc()){
$user = stripslashes($user); //mencegah mysql injection
$pass = stripslashes($pass);
}
$user = mysql_real_escape_string($user);
$pass = mysql_real_escape_string($pass);
$result=mysql_query("SELECT * FROM user WHERE username='$user' and password='$pass'") or die(mysql_error());
$count=mysql_num_rows($result);
if($count==1)
{
session_register("user");
session_register("pass");
$_SESSION['username']=$_POST['user'];
$_SESSION['id']=mysql_result($result,0,'id');
echo 'correct';
header("location:index.html");
}
else
{
die("id atau password anda salah");
exit();
}
mysql_close($con);
ob_end_flush();
?>
try with this code.
if($count==1)
{
session_register("user");
session_register("pass");
$_SESSION['username']=$_POST['user'];
$_SESSION['id']=mysql_result($result,0,'id');
echo 'Y';
//header("location:index.html");
}
else
{
die("id atau password anda salah");
exit();
}
in javascript:
$.post("check_login.php", dataString, function(data) {
// data is the response sent from the check_login.php
// display the type of data
console.log( typeof data );
console.log( data );
// if data is Y
var reg = /Y/g;
// regex to check the result
if( reg.test(data) ){
console.log('IN');
$('form#memberlogin').hide();
//top.location.href = "index.html";
} else {
console.log('OUT');
// PHP dies message here.
//alert(data);
}
return false;
});
try to check the response in firebug console tab.
Try to use href like,
window.location.href="index.html"
Read this What's the difference between window.location= and window.location.replace()?

Categories