AJAX > PHP Log in not working - php

I'm trying to create a log in form using html > ajax > php, the problem is the php is not working, I don't know where is the problem, I think the ajax cannot execute my php file. I need help. Thanks in advance.
Here is my HTML code: my form and inputs are below
<form id="loginForm">
<input type="text" data-clear-btn="true" name="username" id="username" value="" placeholder="Username / ID No.">
<input type="password" data-clear-btn="true" name="password" id="password" value="" placeholder="Password">
<input type="checkbox" name="rem_user" id="rem_user" data-mini="true">
<label for="rem_user">Remember me</label>
<input type="submit" name="login" id="login" value="Log in" class="ui-btn" />
</form>
<div class="err" id="add_err"></div>
AJAX script that sends request on my php file
<script>
$(document).ready(function(){
$("#loginForm").submit(function(){
var username = $("#username").val();
var password = $("#password").val();
// Returns successful data submission message when the entered information is in database.
var dataString = 'username=' + username + '&password=' + password;
if (username == '' || password == ''){
alert("Please Fill All Fields");
}
else {
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "php/login-action.php",
data: dataString,
success: function(result){
window.location="#report_page";
}
});
}
return false;
});
});
</script>
PHP File
<?php
require "includes/connection.php";
include "includes/function.php";
if(isset($_POST['login'])){
$username = $_POST['username'];
$password = $_POST['password'];
$username = sanitize($username);
$password = sanitize($password);
$pass2 = md5($password);
$salt = "sometext";
$validateHash = $salt.$pass2;
$pass = hash("sha512", $validateHash);
$sql = "SELECT * FROM user_login WHERE username='".$username."' and password='".$password."'";
$result = mysqli_query($con,$sql) or die("Error: ". mysqli_error($con));
$count=mysqli_num_rows($result);
while($row=mysqli_fetch_array($result))
{
$id = $row['user_id'];
$username = $row['username'];
$name = "".$row['firstname']." ".$row['lastname']."";
$acc_type = $row['Acc_Type'];
}
if($count==1){
if($acc_type == 'user') {
$_SESSION["id"] = $id;
$_SESSION["username"] = $username;
$_SESSION["name"] = $name;
echo 'true';
}
else {
echo 'false';
}
}
}
?>

as Cattla mentioned in comments.
Your PHP is looking for $_POST['login'], and your $.ajax call didn't pass that in.
so here is the answer
var dataString = 'login=login&username=' + username + '&password=' + password;
Debug tips
Did ajax send all required inputs to PHP (you can inspect this from browser developer tool)
Did php receive all required inputs (you could var_dump($_POST)
Did php connect to mysql successfully
Did ajax receive data from PHP (use alert or console.log)

try this, and if you get error state what it is
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#loginForm").submit(function(){
if (username == ' ' || password == ' '){
alert("Please Fill All Fields");
}
else {
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "php/login-action.php",
data: $(this).serialize(),
success: function(result){
alert('sucess'); //window.location="#report_page";
}
});
}
return false;
});
});
</script>

Related

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 to check if jquery ajax send POST request or not?

I have created a simple Login Register program using PHP.
Now I am trying to validate if username already exists or not using jquery ajax. The jquery code runs but keeps on showing 'Checking Availability'.
Here is the code I have used. Please ignore the vulnerability and other errors in my PHP code ( which may not affect jquery ajax process ) as I am new to this. I'm working for improving those things.
Register.php
<?php
include('config.php');
if(isset($login_session))
{
header("Location: login.php");
}
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$username = mysqli_real_escape_string($obj->conn,$_POST['username']);
$password = mysqli_real_escape_string($obj->conn,$_POST['password']);
$name = mysqli_real_escape_string($obj->conn,$_POST['name']);
$email = mysqli_real_escape_string($obj->conn,$_POST['email']);
$password = md5($password);
$sql ="SELECT uid from users WHERE username = '$username' or email = '$email'";
$register_user = mysqli_query($obj->conn,$sql) or die(mysqli_error($sql));
$no_rows = mysqli_num_rows($register_user);
if($no_rows == 0)
{
$sql2 = "INSERT INTO users(username, password, name, email) values ('$username', '$password', '$name', '$email')";
$result = mysqli_query($obj->conn, $sql2) or die(mysqli_error($sql2));
echo "Registration Successfull!";
}
else{
echo "Registration Failed.";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/username.js"></script>
</head>
<body>
<form action="register.php" method="post">
<label>UserName:</label>
<input type="text" id="username" name="username" required/>
<span id="status"></span><br />
<label>Password :</label>
<input type="password" name="password" required/><br/>
<label>Full Name :</label>
<input type="text" name="name" required/><br/>
<label>Email :</label>
<input type="email" name="email" required/><br/>
<input type="submit" value=" Submit "/><br />
</form>
</body>
</html>
username.js
$(document).ready(function()
{
$("#username").change(function()
{
var username = $("#username").val();
var msgbox = $("#status");
if(username.length > 3)
{
$("#status").html('<img src="img/loader.gif" align="absmiddle"> Checking availability...');
$.ajax({
type: "POST",
url: "php/username-check.php",
data: "username="+ username,
success: function(msg){
$("#status").ajaxComplete(function(event, request){
if(msg == 'OK')
{
msgbox.html('<img src="img/yes.png" align="absmiddle"> <font color="Green"> Available </font> ');
}
else
{
$("#username").removeClass("green");
$("#username").addClass("red");
msgbox.html(msg);
}
});
}
});
}
else
{
$("#status").html('<font color="#cc0000">Enter valid User Name</font>');
}
return false;
});
});
username-check.php
<?php
include("config.php");
if(isSet($_POST['username']))
{
$username = $_POST['username'];
$username = mysqli_real_escape_string($obj->conn,$username);
$sql = "SELECT username FROM users WHERE username='$username'";
$sql_check = mysqli_query($obj->conn,$sql);
if (!$sql_check)))
{
echo 'could not complete query: ' . mysqli_error($obj->conn,$sql_check);
}else{
echo 'query successful!';
}
if(mysqli_num_rows($obj->conn,$sql_check))
{
echo '<font color="#cc0000"><b>'.$username.'</b> is already in use.</font>';
}
else
{
echo 'OK';
}
}
?>
and I want to know if there is a way to check if jQuery Ajax sent the POST request to that file or not?
You are confusing ajax functions...Syntax will be like this
$.ajax({
url: url,
data: data,
type: "POST",
beforeSend: function () {
},
success: function (returnData) {
},
error: function (xhr, ajaxOptions, thrownError) {
},
complete: function () {
}
});
Examine the request using a browser utility
- Launch the chrome browser
- Right click and select inspect element menu
- click on Network tab
- Load your URL
- Perform the Ajax request
- You can see the request here (new request will be last in the list).
- Click on it
- Right side window shows you request and response data
You did correct.Easy way to check them is use firebug tool on your browser...I recommend firefox with firebug.install it first and then open it before you post your form.then goto console log and send your form...Check it out,best software.

Ajax Post with PHP and MySQL

Im trying to post data to mysql by using PHP and Ajax, the only thing problem that data does not enter into database it so the problem seems in the javascript which i think ajax please help me.
Please there some one can fix it if there any error on code?
FORM:
<form id="contactForm" action="ajax.php" method="post">
<input name="name" id="name" type="text"/>
<input name="email" id="email" type="text"/>
<input type="button" value="Send" name="submit" id="submit" />
<span id="error" class="warning">Message</span></p>
</form>
<p id="sent-form-msg" class="success">Thanks for your comments.We will update you within 24 hours. </p>
JS:
jQuery(document).ready(function($){
// hide messages
$("#error").hide();
$("#sent-form-msg").hide();
// on submit...
$("#contactForm #submit").click(function() {
$("#error").hide();
var name = $("input#name").val();
if(name == ""){
$("#error").fadeIn().text("Name required.");
$("input#name").focus();
return false;
}
var email = $("input#email").val();
if(email == ""){
$("#error").fadeIn().text("Email required");
$("input#email").focus();
return false;
}
var dataString = 'name=' + name + '&email=' + email;
$.ajax({
type:"POST",
data: dataString,
success: success()
});
});
// on success...
function success(){
$("#sent-form-msg").fadeIn();
$("#contactForm").fadeOut();
}
return false;
});
AJAX.php
$con=mysqli_connect("localhost","admin","admin","test");
$name = mysqli_real_escape_string($con, $_POST['name']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$sql="INSERT INTO test (name, email) VALUES ('$name', '$email')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
Thank you in Advance.
You must include the URL you want to POST to in the AJAX call.
$.ajax({
url: "ajax.php",
type:"POST",
data: dataString,
success: success()
});
Here is what I suggest doing:
HTML:
<input name="name" id="name" type="text"/>
<input name="email" id="email" type="text"/>
<input type="button" value="Send" onclick="validate();" id="submit" />
<span id="error" class="warning">Message</span></p>
<p id="sent-form-msg" class="success">Thanks for your comments.We will update you within 24 hours. </p>
Javascript:
jQuery(document).ready(function($){
// hide messages
$("#error").hide();
$("#sent-form-msg").hide();
}
// on submit...
function validate()
{
$("#error").hide();
var name = $("#name").val();
if(name == ""){
$("#error").fadeIn().text("Name required.");
$("input#name").focus();
}
var email = $("#email").val();
if(email == ""){
$("#error").fadeIn().text("Email required");
$("input#email").focus();
return false;
}
// var dataString = 'name=' + name + '&email=' + email;
$.ajax({
url: "phpScript.php"
type:"POST",
data: {name:name, email:email},
success: success()
});
});
// on success...
function success(){
$("#sent-form-msg").fadeIn();
$("#contactForm").fadeOut();
}
}
PHP:
$con = mysqli_connect("localhost","admin","admin","test");
$name = $_POST['name'];
$email = $_POST['email'];
$sql = "INSERT INTO test (name, email) VALUES ('$name', '$email')";
//I like to do it like this:
$result = mysql_query($query, $connect);
/*if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}*/
echo "1 record added";
mysqli_close($con);
I give credit also to the other answer by mattmemo. The thing he corrected was definitely a mistake. I think there may have been other mistakes in MARGELANI's script so I chose to post my answer as well. If this script doesn't work let my know and I will recode it. Good luck! :D

jQuery AJAX shown form validation errors

I got problem with shown validation error on below script, for example what I tested, I enter a correct email and wrong password, the request will returned both Wrong email address and Wrong password under each input textbox, it is not only Wrong Password is expected to shown, I tried hardcode required data in request.php and run this script directly, for either giving wrong data in in $_POST, the console response {"error":{"lemail":"Wrong email address","lpassword":"Wrong password"}}, can someone please have a look in my code what's goes wrong?
form with AJAX call:
<body>
<form role="form" method="post" id="login_form" enctype="multipart/form-data">
<div class="modal-body">
<div class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control" id="lemail" name="lemail" placeholder="Your email"><span class="error" id="lemail_error"></span>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="lpassword" name="lpassword" placeholder="Password"><span class="error" id="lpassword_error"></span>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success" id="btn_login" data-loading-text="Loading...">Sign In</button>
</div>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#btn_login').click(function(){
var parameters = $('#login_form').serialize();
$.ajax({
url: 'inc/callback/request.php',
type: 'POST',
data: {'parameters' : parameters},
dataType: 'json',
success: function(response){
if(response.success == 'logged'){
$('#login_form')[0].reset();
alert(response.success);
}else if(response.inactivate == 'inactive'){
alert('Your account is inactive!');
}else{
$('[id$="_error"]').html(''); //clear valid error msg
// display invalid error msg
$.each(response.error, function(key, value){
if(value){
$('#' + key + '_error').html(value);
}
});
}
},
error: function(){
console.log(arguments);
}
});
});
});
</body>
request.php
parse_str($_POST['parameters'], $output);
$email = $mysqli->real_escape_string(strtolower(trim($output['lemail'])));
$password = $mysqli->real_escape_string(trim($output['lpassword']));
$func = new Functions();
$message = array();
//validate user's email and password from database
$check = $mysqli->query("SELECT * FROM `users` WHERE user_email='".$email."' AND user_password='".sha1(sha1($password))."'") or die($mysqli->error);
$rows = $check->fetch_array(MYSQLI_BOTH);
$num = $check->num_rows;
$uId = $rows['user_id'];
$uEmail = $rows['user_email'];
$uPwd = $rows['user_password'];
$uType = $rows['account_type'];
$uStatus = $rows['account_status'];
// validate user's account
if(empty($email) || $email !== $uEmail){
$message['error']['lemail'] = 'Wrong email address';
}
if(empty($password) || sha1(sha1($password)) !== $uPwd){
$message['error']['lpassword'] = 'Wrong password';
}
if(!isset($message['error'])){
if($uStatus == 0){
$message['inactivate'] = 'inactive';
}else{
$message['success'] = 'logged';
}
}
echo json_encode($message);
Edited:
Solved! nothing went wrong, just out of logic on variables comparison!! ;P
in you php code first you have to deserliazed ur code.. put these lines at top..
$searcharray = array();
parse_str($_POST[parameters], $searcharray);
$email = $mysqli->real_escape_string(strtolower(trim($searcharray['lemail'])));
$password = $mysqli->real_escape_string(trim($searcharray['lpassword']));
You are posting string not array, you need to use parse_str function first.
Remove this enctype="multipart/form-data" from form
<form role="form" method="post" id="login_form">
Replace your data: line with this
data: {'parameters' : parameters},
After add this to your PHP
parse_str($_POST['parameters'], $output);
$email = $mysqli->real_escape_string(strtolower(trim($output['lemail'])));
$password = $mysqli->real_escape_string(trim($output['lpassword']));

JQuery is not picking up echo from php

I'm echoing a message ('ok') from a PHP script to a JQuery ajax call.
I'm echoing out the correct message, and its showing up in the console when i log it, but the appropriate jquery function is not firing - according to the code i should get an Your password has been changed successfully" message, but I only get a "there was a problem" message - can anyone suggest a reason why?
here is the code first the PHP:
if(isset($_POST['oldpass'])){
$oldpass = mysql_real_escape_string($_POST['oldpass']);
$newpass = mysql_real_escape_string($_POST['newpass']);
$sql = "SELECT password, salt FROM users WHERE email='$log_email' AND id='$log_id' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$numrows = mysqli_num_rows($query);
if($numrows > 0){
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$current_salt = $row["salt"];
$db_pass = $row["password"];
}
$old_pass_hash = crypt($oldpass, $current_salt);
if ($old_pass_hash != $db_pass){
echo "problem";
exit();
}
}
$s = "$2a$10$";
$random = randStrGen(20);
$salt = $s.$random;
$p_crypt = crypt($newpass, $salt);
$sql = "UPDATE users SET password='$p_crypt', salt='$salt' WHERE email='$log_email' AND id='$log_id' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
if ($query == true){
$_SESSION['password'] = $p_crypt;
echo 'ok';
exit();
}
}
?>
This is the javascript/JQuery
function change_password(){
var oldpass = $('#old_pass').val();
var newpass = $('#new_pass').val();
var newpass_conf = $('#confirm_new_pass').val();
if(newpass != newpass_conf){
$('#status').html("Your passwords do not match");
} else if(newpass=="" || oldpass==""){
$('#status').html("You have not entered anything");
}
$.ajax({
type: 'POST',
url: "changePassword.php",
dataType: 'text',
data: {
"oldpass": oldpass,
"newpass": newpass_conf },
success:function(data){
if(data == "ok"){
$('#change_password_form').html("<h2> Success</h2><div class='noerror'><p> Your password has been changed successfully.</p> <p> You may now close this window.</p></div>");
} else {
$('#status').html("There was a problem");
}
}
});
}
$(document).ready(function(){
$(document).on('click','#change_password', function(){
change_password();
});
});
</script>
and finally the html
<div> <h1>Change your password</h1></div><hr>
<form id="change_password_form" class="input" onsubmit="return false;">
<div> <label for="old_pass">Current Password:</label>
<input id="old_pass" type="text" class="searchbox" onfocus="emptyElement('status')" maxlength="88" value=""></div>
<div> <label for="new_pass">New Password:</label>
<input id="new_pass" class="searchbox" type="text" onfocus="emptyElement('status')" maxlength="88" value=""> </div>
<div><label for="confirm_new_pass">Confirm New Password:</label>
<input id="confirm_new_pass" class="searchbox" type="text" onfocus="emptyElement('status')" maxlength="88" value=""><div>
<input type="button" style="position:relative;top:10px; float:right;" id="change_password" value="Change Password"></form>
<span id="status" class="statuserror"></span>
</body>
</html>
change the dataType: "json" in your ajax call
then in your php code return json data
json_encode(array('response'=>'ok'));
your ajax success function should look like this,
success: function (data) {
var resultObject = jQuery.parseJSON(data);
if(rersultObject['response']=='ok') {
$('#change_password_form').html("<h2> Success</h2><div class='noerror'><p> Your password has been changed successfully.</p> <p> You may now close this window.</p></div>");
} else {
$('#status').html("There was a problem");
}
}
}`
here parseJSON is used to convert JSON string to javascript object.
I got this problem a while ago and could never figure it out, although different scenario. What I did was to change the data type to json like so:
$.ajax({
type: 'POST',
url: url,
data: 'data=data&other=other'
dataType: 'json',
//if everything goes out as planned
success: function(response) {
alert(response['data']);
}
});
and in the php
$respond = array("data" => 'ok',
"other" => 'whatever else'
);
echo json_encode($respond); //send a response back to javascript
exit();

Categories