Return value from ajax form - php

I have a login form in php. I have used ajaxform so that the page does not get reloaded when the username or password is wrong. I have another page checklogin.php which checks whether the username and pw is there in the database and it returns the count of the number of rows. I want to compare the count in the login.php and display the error message if the count=1 and redirect to another page if count=2. I tried to display the count in an errordiv using target: 'errordiv' and checking its innerHTML but it failed to do so.
My login.php
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script type="text/javascript" src="scripts/jquery.form.js"></script>
<!--Slider-in icons-->
<script type="text/javascript">
function checklogin()
{
var request=$("#login-form").ajaxForm(
{
target:'#errordiv'
}).abort();
request.submit();
var divmsg=document.getElementById("errordiv");
if (divmsg.childNodes[0].nodeValue == "1")
{
divmsg.childNodesp[0].nodeValue="Sorry";
alert ("Invalid username or password");} //I didn't get the alert as well a the divmsg content didn't change
};
</script>
</head>
<body>
<!--WRAPPER-->
<div id="wrapper">
<!--LOGIN FORM-->
<form name="login-form" id="login-form" class="login-form" action="checklogin.php" method="post">
<!--CONTENT-->
<div class="content">
<!--USERNAME--><input name="un" type="text" class="input username" placeholder="Username" onfocus="this.value=''" required="required" /><!--END USERNAME-->
<!--PASSWORD--><input name="pw" type="password" class="input password" placeholder="Password" onfocus="this.value=''" required="required" /><!--END PASSWORD-->
</div>
<!--END CONTENT-->
<!--FOOTER-->
<div class="footer">
<!--LOGIN BUTTON--><input type="submit" name="submit" value="Login" class="button" onclick="checklogin()" /><!--END LOGIN BUTTON-->
</div>
<!--END FOOTER-->
</form>
<div id="errordiv" class="errordiv"></div>
<!--END LOGIN FORM-->
checklogin.php
<?php
include ('dbconn.php');
$user = trim($_POST['un']);
$pass = trim($_POST['pw']);
$user = mysql_real_escape_string($user);
$pass = mysql_real_escape_string($pass);
$result=mysql_query("select Id from login where Username='$user' and Password='$pass'") or die (mysql_error());
$result= mysql_fetch_assoc($result);
$num= count ($result);
echo $num;
?>
How can I get the value of $num in login.php without displaying it to a div and compare the value of $num and accordingly display the errormsg in errordiv or if $num==2 redirect to another page.

Change your code to include the code which change the div and provide alert to be included in the callback.
var request=$("#login-form").ajaxForm(
{
target:'#errordiv',
success: function (html) {
if ($("#errordiv).html() == "1") {
$("#errordiv).html("Sorry");
alert ("Invalid username or password");
}
}
}).abort();
request.submit();

Maybe try to make the checking request asynchronously and process user feedback in AJAX callback:
JS:
$(function(){
$("#login-form").ajaxForm(function(response){
if(response.count===1){
$("#errordiv").html("msg you want to show");
}else if(response.count===2){
//redirect
}
});
});
php:
<?php
header("Content-Type: application/json");
//your database check logic
$user = trim($_POST['un']);
$pass = trim($_POST['pw']);
$user = mysql_real_escape_string($user);
$pass = mysql_real_escape_string($pass);
$result=mysql_query("select Id from login where Username='$user' and Password='$pass'") or die (mysql_error());
$result= mysql_fetch_assoc($result);
$num= count ($result);
//and return response in JSON
echo json_encode(array("count"=>$num));
?>
Hope this is helpful for you.
[EDIT]
remove the form submit button inline JS function invoking:
onclick="checklogin()"
and put checklogin function logic to document ready callback, initialize the form when the DOM is ready

Related

AJAX Login without refresh

I have a login form and a AJAX Script to login without being redirected to the php script. It works great but there is just one small problem. When i submit the login form it prints out the output from php file (As expected) and it says that im online (As written in php script if the login details is correct). But i am not actually online until i refresh the page...
So my question is how can i use AJAX for a login form that prevents me from being redirected to php script but it logs me in to website without a page refresh.
So here is the AJAX Script
$(document).ready(function() {
$('.AJAXForm').submit(function (event) {
var data = $(this);
$.ajax({
type: data.attr('method'),
url: data.attr('action'),
data: data.serialize(),
success: function (data) {
$('.output').html(data);
$('.AJAXForm input:NOT([type=submit])').val('');
}
});
event.preventDefault();
});
});
And here is my html form
<div class="output"></div>
<form action="functions/login.php" class="AJAXForm" method="post">
<div class="form-group">
<label for="login-user">Username:</label>
<input type="text" class="form-control input" name="user" id="login-user">
</div>
<div class="form-group">
<label for="login-pass">Password:</label>
<input type="password" class="form-control input" name="pass" id="login-pass">
</div>
<input type="submit" value="Create Account" name="submit">
</form>
And here is my php script
<?php
session_start();
include("../config/dbconf.php");
function encryptsha($user, $pass) {
$user = strtoupper($user);
$pass = strtoupper($pass);
return sha1($user.":".$pass);
}
$pass = encryptsha($_POST['user'], $_POST['pass']);
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ? AND sha_pass = ?");
$stmt->bind_param("ss", $_POST['user'], $pass);
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows > 0) {
$_SESSION['username'] = $_POST['user'];
echo "<div class='alert-success'><strong>Success!</strong> Welcome back ".$_POST['user']."</div>";
}else{
echo "<div class='alert-error'><strong>Error!</strong> Something went wrong, please try again.</div>";
}
?>

redirect is not going to separate page

I have a sign in page that uses Ajax to send username and password to a php file to verify. If the verification fails, it sends a message back to the user stating this on the sign in page under the create account button. This is good. If the user/password is correct, I want to redirect to the users account page. This is working also, but it is ending up in the same place as the failed verification - on the sign in page under the create account button. I understand why this is happen, I am not sure how to get the redirect to just show the new page on it's own page. Thanks
See for yourself - kyzereyephotography.com/examples/signIn/signIn.php
username/pass - 123#123.com / 123
use an incorrect password to see the failed message
Here is the code:
signIn.php
<!DOCTYPE html>
<html>
<head>
<title>Sign IN</title>
<link href="../dist/css/bootstrap.css" rel="stylesheet">
<link href="../dist/css/signin.css" rel="stylesheet">
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
</head>
<body>
<!-- Fixed navbar -->
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="../">Code Example - Log In</a>
</div>
</div>
</div> </br></br>
<!-- Sign In Form -->
<div class="container">
<form class="form-signin" id="login_form" action="checkLogin.php" method="post">
<p>
This bit of code asks you to log in. If you do not have an account, you can create one and then log on to it.
</p>
<h2 class="form-signin-heading">Please sign in</h2>
<input name="username" id="username" type="text" class="form-control" placeholder="Email address" required autofocus>
<input name="password" id="password" type="password" class="form-control" placeholder="Password" required>
<button id="signin" class="btn btn-lg btn-primary btn-block" type="submit" >Sign in</button>
</form>
<!-- Create Accout Form -->
<form class="form-signin">
<input class="btn btn-lg btn-primary btn-block" type="button" value = "Create Account" onclick="window.location.href='createAccount.php'"/>
</form>
<span id="badpass"></span> <!--place to put the error message if password or username is bad-->
</div> <!-- /container -->
<!-- JavaScript-->
<!-- this script is used to validate the username and password. JavaScript is used to pass data to checklogin.php-->
<script type="text/javascript">
$("#signin").click( function() {
var data = $("#login_form :input").serializeArray();
$.post( $("#login_form").attr("action"), data, function(info) { $("#badpass").html(info);});
});
$("#login_form").submit(function() {
return false;
});
</script>
</body>
</html>
checkLogin.php
<?php
session_start();
include "includes/dbconnect.php";
$username = $_POST['username'];
$userPassword = $_POST['password'];
$query1 = "SELECT first_name, last_name, password FROM profiles WHERE email = '$username'";
$results1 = mysql_query($query1,$dbconnect) or die ("Error in query1. ". mysql_error($dbconnect));
$row = mysql_fetch_assoc($results1);
$count = mysql_num_rows($results1);
$hashedPass = $row['password'];
if($count == 1)
{
if (crypt($userPassword, $hashedPass) == $hashedPass)
{
$_SESSION["username"] = $username;
header("location: profilesPage.php");
die();
}
else
{
echo "<div style='color: red; font-size: 20px; text-align: center;'>ID or Password does not match</div>";
}
exit();
}
else
{
echo "<div style='color: red; font-size: 20px; text-align: center;'>Bad username or password</div>";
}
?>
First of all: Please update your script to MySQLi() or PDO() for security reasons! Mysql is deprecated!
Next my approach for your problem would be something like this:
$("#signin").click( function() {
var data = $("#login_form :input").serializeArray();
$.post(
$("#login_form").attr("action"),
data,
function(info) {
if(info == ""){ //Insert good password response here
window.location.href = ""; //Url to profile page here
} else {
$("#badpass").html(info);
}
}
);
});

AJAX form Validation Error

I'm developing a simple login form but with advanced features in that. On submitting the form I want to validate it with AJAX and display the error message in the respective "SPAN class="error". The problem is i'm not getting the validation error when i submit the form. The following is the code i've tried. Please help..
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<link rel="shortcut icon" href="_images/Favicon.png"/>
<title>18+</title>
<link href="_css/login.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="_scripts/jquery.tools.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#username').focus(); Focus to the username field on body loads
$('#submit').click(function(){ // Create `click` event function for login
var username = $('#username'); // Get the username field
var password = $('#password'); // Get the password field
var login_result = $('.login_result'); // Get the login result div
var username = $('.username'); // Get the username error div
var password = $('.password'); // Get the password error div
if(username.val() == ''){ // Check the username values is empty or not
username.focus(); // focus to the filed
username.html('<span class="error">Enter the Username...</span>');
return false;
}
if(password.val() == ''){ // Check the password values is empty or not
password.focus();
password.html('<span class="error">Enter Your Password...</span>');
return false;
}
if(username.val() != '' && password.val() != ''){
var UrlToPass = 'action=login&username='+username.val()+'&password='+password.val();
$.ajax({ // Send the credential values to another checker.php using Ajax in POST menthod
type : 'POST',
data : UrlToPass,
url : 'checker.php',
success: function(responseText){ // Get the result and asign to each cases
if(responseText == 0){
login_result.html('<span class="error">The Username Or Password You Entered Is Incorrect...</span>');
}
else if(responseText == 1){
window.location = 'admin.php';
}
else{
alert('Problem with sql query');
}
}
});
}
return false;
});
});
</script>
</head>
<body>
<div id="logo"></div>
<div id="container">
<div id="form">
<form action="" method="post" id="user_login" name="user_login" enctype="multipart/form-data">
<p id="head">User Login</p>
<div class="row">
<span class="error" class="login_result" id="login_result"></span>
</div>
<div class="row">
<div class="input">
<input type="text" id="username" name="username" class="detail" placeholder="Username" spellcheck="false" title="Enter Your Username.."/>
<span class="error" id="username">Enter Your Username....</span>
</div>
</div>
<div class="row">
<div class="input">
<input type="password" id="password" name="password" class="detail" placeholder="Password" spellcheck="false" title="Enter Your Password.."/>
<span class="error" id="password">Enter Your Password...</span>
</div>
</div>
<p class="submit">
<button type="submit" id="submit" name="submmit" value="Register">Login</button>
</p>
</form>
</div>
</div>
</div>
</div><!--end container-->
<div id="formfooter">
<div class="input">
Copyright © CompanyName.
</div>
</div>
</body>
</html>
You should prevent the default action when you catch the event in javascript:
....
$('#submit').click(function(e){ // Create `click` event function for login
e.preventDefault(); //Prevent the default submit action of the form
var username = $('#username'); // Get the username field
var password = $('#password'); // Get the password field
var login_result = $('.login_result'); // Get the login result div
....
First, you have two same ids on your HTML form.
<input type="text" id="username" .../>
<span class="error" id="username">....
Take a look above and you can see that there are two ids username. You should change the id attribute with class attribute so it become
<span class="error" class="username">....
Second, on your javascript you have same variables assigning.
var username = $('#username');
var password = $('#password');
.....
var username = $('.username');
var password = $('.password');
Username and password are already taken. Change that into different variable name.
Third, I suggest you to use this awesome jquery form validation library http://jqueryvalidation.org/
Good luck :)

Login Form for mobile application using Jquery Mobile, PHP and MySQL

I am new with mobile development. I am trying to develop a Login Form that will check username and password with MySQL database. I built some code already. I have two problems. The first one is, after submitted the form, in the browser's URL bar, I can see the username and password typed, even using POST on my JQuery script. The second issue is that the page keeps going back to login.html instead going to main.html. Below is what I built, using my actual experience with PHP, JQuery and MySQL.
HTML form
<div id="loginPage" data-role="page">
<div data-role="header">
<h1>App Authentication</h1>
</div>
<div data-role="content">
<div id="landmark-1" data-landmark-id="1">
<form id="loginForm">
<div data-role="fieldcontain" class="ui-hide-label">
<label for="username">Username:</label>
<input type="text" name="username" id="username" value="" placeholder="Username" />
</div>
<div data-role="fieldcontain" class="ui-hide-label">
<label for="password">Password:</label>
<input type="password" name="password" id="password" value="" placeholder="Password" />
</div>
<input type="submit" value="Login" id="submitButton">
</form>
</div>
</div>
<div data-role="footer">
<h4>© Silva's General Services</h4>
</div>
The auth.php
<?php
$mysqli = new mysqli($mysql_hostname,$mysql_user, $mysql_password, $mysql_database);
header("access-control-allow-origin: *");
header("access-control-allow-methods: GET, POST, OPTIONS");
header("access-control-allow-credentials: true");
header("access-control-allow-headers: Content-Type, *");
header("Content-type: application/json");
// Parse the log in form if the user has filled it out and pressed "Log In"
if (isset($_POST["username"]) && isset($_POST["password"])) {
CRYPT_BLOWFISH or die ('No Blowfish found.');
//This string tells crypt to use blowfish for 5 rounds.
$Blowfish_Pre = '$2a$05$';
$Blowfish_End = '$';
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$sql = "SELECT id, password, salt, username FROM users WHERE username='$username' LIMIT 1";
$result = $mysqli->query($sql) or die( $mysqli->error() );
$row = mysqli_fetch_assoc($result);
$hashed_pass = crypt($password, $Blowfish_Pre . $row['salt'] . $Blowfish_End);
if ($hashed_pass == $row['password']) {
$response_array['status'] = 'success';
} else {
$response_array['status'] = 'error';
}
echo json_encode($response_array);
}
$mysqli->close();
?>
Jquery Script
<script>
$('#loginForm').submit(function(){
e.preventDefault();
jQuery.support.cors = true;
$.ajax({
url: 'http://www.test.com/mobile/auth.php',
crossDomain: true,
type: 'post',
data: $("#loginForm").serialize(),
success: function(data){
if(data.status == 'success'){
window.location.href = 'http://www.test.com/mobile/main.html';
}else if(data.status == 'error'){
alert("Authentication Invalid. Please try again!");
return false;
}
}
});
});
</script>
I really appreciate any help.
Thank you.
This is simply a guess, but:
you have no method in your form declaration: <form action="your_action_url" method="post">.
it looks like your not passing the event in the function. I know the syntax looking like this: $('#loginForm').submit(function(e){ notice the "e" as function parameter
jquery has e.preventDefault and e.stopPropagation which are two separate things, see jquery event object. Some other handlers may be doing stuff. You can also use "return false;" instead of the two, depending on your use case.
I think 2. will fix your problem, you need to pass the event to the function.

login form running script without refreshing page, but need to remove form once successful

The code below gets the username/password and runs it thru the backend.php script.
<?php session_start(); ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#login_form").submit(function() {
var unameval = $("#username").val();
var pwordval = $("#password").val();
$.post("backend.php", { username: unameval,
password: pwordval }, function(data) {
$("#status p").html(data);
});
return false;
});
});
</script>
</head>
<body>
<?php
if(isset($_SESSION['user_session'])) {
print '<p>user '.$_SESSION['user_session'].' logged in</p>';
} else { ?>
<form id="login_form" method="post">
<p>Username: <input type="text" id="username" name="username" /></p>
<p>Password: <input type="password" id="password" name="password" /></p>
<p><input type="submit" value="Login" /></p>
</form>
<div id="status">
<p></p>
</div> <?php
}?>
</body>
</html>
It authenticates the user properly, but what I want it to is hide the form once successful.
Here is what the page looks like before the form is submitted: http://grab.by/3hoH
Here is the page after the form was successfully submitted: http://grab.by/3hoR
I think I need to run some javascript to check for success, then if success, do not display form, if !success, display form.
I am unsure on how to do that, if that is the case.
backend.php code
<?php
session_start();
ini_set('display_errors',1);
error_reporting(E_ALL);
require_once('adLDAP.php');
//header('Content-type: text/json');
$adldap = new adLDAP();
if(isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password']; // associated password
// connect to ldap server
$authUser = $adldap->authenticate($username, $password);
if ($authUser === true) {
print "<p>authuser true</p>";
$_SESSION['user_session'] = $username;
if(isset($_SESSION['user_session'])) {
print "<p>session is set</p>";
}
}
else {
print "<p>User authentication unsuccessful</p>";
}
}
?>
You need to check the response to see if the login succeeded, and, if it did, remove the login form.
You can remove the login form by writing
$('#login_form').remove();
To check whether the login succeeded, you should change your server-side script to return a JSON object that indicates whether the login succeeded and contains a message.
For example:
{ success: true, message: "You have successfully logged in" }

Categories