Ajax mysqli not working - php

Can anyone tel me what went wrong?
This is my code :
body.html
<div class="container">
<div id="login_form">
<form action="login.php" class="form-signin">
<h3 class="form-signin-heading">Sign in</h2>
<div class="err" id="add_err"></div>
<label for="inputUser" class="sr-only">Email address</label>
<input type="text" name="inputUser" id="inputUser" class="form-control" placeholder="Username" required autofocus>
<label for="password" class="sr-only">Password</label>
<input type="password" name="password" id="password" class="form-control" placeholder="Password" required>
<div class="checkbox" style="padding-top:20px;">
<label>
<input type="checkbox" value="remember-me"> Remember me</input>
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" id="login" type="submit">Sign in</button>
Cancel
</form>
</div>
<div id="shadow" class="popup"></div>
</div>
<script src="myjs/myjs.js">
</script>
myjs.js
$(document).ready(function(){
$("#login").click(function(){
$("#add_err").removeClass("alert");
$("#add_err").addClass("alert");
$("#add_err").removeClass("alert-danger");
$("#add_err").addClass("alert-info");
if($("#inputUser").val() == "")
{
$("#add_err").removeClass("alert-info");
$("#add_err").addClass("alert-danger");
$("input[name='password']").val("");
$("#add_err").html("User Empty")
}
else if($("#password").val() == "")
{
$("#add_err").removeClass("alert-info");
$("#add_err").addClass("alert-danger");
$("input[name='password']").val("");
$("#add_err").html("Password Empty")
}
else{
username=$("#inputUser").val();
password=$("#password").val();
$.ajax({
type: "POST",
url: "login.php",
data: "name="+username+"&pwd="+password,
success: function(html){
if(html=='true')
{
window.location.href = "example/admin.html";
}
else
{
$("#add_err").removeClass("alert-info");
$("#add_err").addClass("alert-danger");
$("input[name='password']").val("");
$("#add_err").html("Wrong username or password");
}
},
beforeSend:function()
{
$("#add_err").html("Loading...")
}
});
}
return false;
});
});
login.php
<?php
session_start();
$username = $_POST['name'];
$password = md5($_POST['pwd']);
$mysqli=mysqli_connect('localhost','root','','whatever');
$query = "SELECT * FROM user WHERE username='$username' AND password='$password'";
$result = mysqli_query($mysqli,$query)or die(mysqli_error());
$num_row = mysqli_num_rows($result);
$row=mysqli_fetch_array($result);
if( $num_row >=1 ) {
echo 'true';
$_SESSION['user_name']=$row['username'];
}
else{
echo 'false';
}
?>
This code is working!
But when I change the "login.php" with OOP way not procedural like this:
<?php
session_start();
$username = $_POST['name'];
$password = md5($_POST['pwd']);
$con = new mysqli("localhost", "root", "", "whatever");
$query = "SELECT * FROM user WHERE username='$username' AND password='$password'";
$result = $con->query($query);
$num_row = $result->num_rows;
$row=$result->fetch_array();
if( $num_row >=1 ) {
echo 'true';
$_SESSION['user_name']=$row['username'];
}
else{
echo 'false';
}
?>
It did not work. Can anyone tell me what went wrong?

Without closely examining your code, the most obvious difference is you didn't use session_start() in the second script; meaning there isn't any session to store the username in...

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.

using ajax to login with php

I am trying to use window.location = "userpage.php"; after a successful login but the page does not redirect.
I am using Ajax and a modal form in my code
Everything works fine. I don't get any errors. I check the network headers. and there is no response in the network
I have not been able to figure out the issue.
I have tried
window.location.href
window.location.replace.
Nothing is working
need help
Thanks
This is part of the js file
$("#loginform").submit(function(event) {
//prevent default php processing
event.preventDefault();
//collect user inputs
var datatopost = $(this).serializeArray();
//send them to login.php using AJAX
$.ajax({
url: "login.php",
type: "POST",
data: datatopost,
success: function(data) {
if (data == "success") {
window.location = "user_page.php";
} else {
$("#loginmessage").html(data);
}
},
error: function() {
$("#loginmessage").html(
"<div class='alert alert-danger'>There was an error with the Ajax Call. Please try again later.</div>"
);$
}
});
});
This is part of my login.php file
//Start session
session_start();
//Connect to the database
include("connection.php");
...
$email = mysqli_real_escape_string($conn, $email);
$password = mysqli_real_escape_string($conn, $password);
$password = hash('sha256', $password);
//Run query: Check combinaton of email & password exists
$sql = "SELECT * FROM users WHERE email='$email' AND password='$password' AND activation='activated'";
$result = mysqli_query($conn, $sql);
if (!$result) {
echo '<div class="alert alert-danger">Error running the query!</div>';
exit;
}
//If email & password don't match print error
$count = mysqli_num_rows($result);
if ($count !== 1) {
echo '<div class="alert alert-danger">Wrong Username or Password</div>';
} else {
//log the user in: Set session variables
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['username'] = $row['username'];
$_SESSION['email'] = $row['email'];
if (empty($_POST['remember'])) {
echo "success";
} else {
// todo logic for remember me
}
}
This is the form modal
//Start session
session_start();
//Connect to the database
include("connection.php");
...
<form method="post" class="login_form modal" id="loginform">
<div class="form-body">
<div class="form-head"><h3>Login form</h3></div>
<div class="form-logo"><img src="/dist/img/logo.svg" alt="" /></div>
<div id="loginmessage"></div>
<div class="form-inputs">
<p><input type="email" name="email" placeholder="email" /></p>
<p><input type="password" name="password" placeholder="Password" /></p>
</div>
<div class="login-session">
<div class="remember">
<input type="checkbox" id="remember" name="remember" value="remember" />
<label for="remember">Remember me</label>
</div>
<div class="">
Forgot my password
</div>
</div>
<div class="form-submit">
<input class="btn btn-primary" type="submit" value="log in"/>
<a class="btn btn-small" href="#signupform" rel="modal:open">register</a>
</div>
</div>
</form>
I finally found the solution to the issue.
In the index.js file:
success: function(data) {
if (data == "success") {
window.location = "user_page.php";`
was changed to:
success: function(data) {
if ($.trim(data) == "success") {
window.location = "user_page.php";`
Because the response message success for some reason had whitespace in it. I trimmed all whitespace and it worked.

How user can change their password after using the hash password and salt?

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";
}
}
}
?>

if statement not working inside ajax

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);
}

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