PHP AJAX form submit no page refresh multiple variable passing - php

fairly new to the language, i have created a simple login system and i am attempting to submit the forms without page refreshes. I have completely created the registration system without page refresh ( coupled with dynamic username checking) and am now attempting to convert the actual login form as well, so that the user can be displayed as logged in without page refresh.
I attempted to use the same method, however now i need to pass both username and password to the validation script, and i am unable to get the password part to work for some reason... although username works fine.
I have it set up to display one error if the password is validated successfully and the other if it is not.. i may be overthinking it, i appreciate your assistance in this possibly trivial problem
PS first go with stack so please point out any suggestions to formatting etc
PHP
<?php
require_once('startsession.php');
$page_title = 'Log In';
require_once('header.php');
require_once('connectvars.php');
require_once('navmenu.php');
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="invisiblelogin.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.error').hide();
$('#Info').hide();
});
function check_login(){
var username = $("#username").val();
var password = $("#password").val();
if(username.length > 0 && password.length > 0){
$.post("logincheck.php", {
username: $('#username').val(),
password: $('#password').val(),
}, function(response){
setTimeout("finishAjax('Info', '"+escape(response)+"')", 450);
});
return false;
}
}
function finishAjax(id, response){
//showing of errors is just visually showing me whether or not the password validation worked
$('#'+id).html(unescape(response));
var valid = $("#Info").html();
if( valid > 0) {
$("label#username_error2").show();
}
else {
$("label#password_error").show();
}
}
</script>
<div id="contact_form">
<form action="" name="contact">
<fieldset><legend>Log In Info</legend>
<font color="red"><div id="Info"></div></font>
<table>
<tr><td><label for="username" id="username_label">Username:</label>
<input type="text" id="username" name="username" value="" class="text-input" /></td>
<td><label class="error" for="username" id="username_error2">Enter your username. </label></td></tr>
<tr><td><label for="password" id="password_label">Password:</label>
<input type="password" id="password" name="password" value="" class="text-input" /> </td>
<td><label class="error" for="password" id="password_error">Enter your password. </label></td></tr></table>
<input type="submit" name="submit" class="button" id="submit_btn" value="Sign Up" onclick="return check_login();" />
</fieldset>
</form>
</div>
<?php
// Insert the page footer
require_once('footer.php');
?>
JS
$(function() {
$('.error').hide();
$(".button").click(function() {
// validate and process form here
$('.error').hide();
var username = $("input#username").val();
var password = $("input#password").val();
if (username == "" || password == "") {
if (username == "") {
$("label#username_error2").show();
$("input#username").focus();
}
if (password == "") {
$("label#password_error").show();
$("input#password").focus();
}
return false;
}
return false;
});
});
Intermediate PHP
<?php
require_once('connectvars.php');
if($_REQUEST)
{
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) or die (mysqli_error());
$username = mysqli_real_escape_string($dbc, trim($_REQUEST['username']));
$password = mysqli_real_escape_string($dbc, trim($_REQUEST['password']));
$query = "SELECT * FROM login_info WHERE username = 'username' AND password = SHA('$password')";
// ------------ THIS PASSWORD PART DOES NOT READ CORRECTLY
$data = mysqli_query($dbc, $query);
if (mysqli_num_rows($data) > 0) {
echo '1';
}
else {
echo '0';
}
}
?>

Ok.. a Few things...
I think you need to troubleshoot the 2 things it could really be... 1) Is the correct value being passed through to the PHP Page? You can check this in the CONSOLE of firebug (an extension for firefox that every developer should have). 2) Is your actual password validation working OK? Hard-code the password. Use the die() function to output data in the PHP page. The result will be seen in firebug as well.
If you're using $.post() on the JS side, your PHP should use $_POST instead of $_REQUEST. Shouldn't impact anything notable, but just thought I would add that.
This code is a little worrying...
if( valid > 0) {
$("label#username_error2").show();
}else {
$("label#password_error").show();
}
Most likely, valid is a string, and will not parse '0' as 0. While a login script is a true/false (0/1) procedure, PHP pages that are called by an ajax function should always return some sort of structure. For example...
Change your POST to expect a json response.
$.post("logincheck.php", {
username: $('#username').val(),
password: $('#password').val(),
}, function(response){
setTimeout(function(){ //Note the change here.
finishAjax('Info', response); //Note the change here.
}, 450); //Note the change here.
}, 'json'); //Note the change here.
Then create a PHP function that will return a json package that your JS will use.
function SendJSONResponse($success, $msg=null, $additionalReturnData=null){
$result = array('success'=>$success);
if ($msg) $result['msg']=$msg;
if ($additionalReturnData) $result=array_merge($reult, $additionalReturnData);
die(json_encode($result));
}
Once you have that, your login script should look more like
if (mysqli_num_rows($data) > 0) {
SendJSONResponse(
true,
null,
array('data'=>$data) //Pass the logged in users info for use in JS
);
}else {
SendJSONResponse(false, 'Username or Password not found');
}
and your JS would look like this...
function finishAjax(id, response){
if( response.success) {
alert('logged in as ' + response.data.full_name + ' (' + response.data.email + ')');
$("label#username_error2").show();
}else {
alert(response.msg);
$("label#password_error").show();
}
}

Related

login with ajax issue

I am trying to create on-page login.
without ajax it works very well. Here is my login.php;
if($_POST)
{
$username =$_POST["username"];
$password =$_POST["password"];
$query = $handler->query("SELECT * FROM members WHERE username='$username' && password='$password'",PDO::FETCH_ASSOC);
if ( $say = $query -> rowCount() ){
if( $say > 0 ){
session_start();
$_SESSION['session']=true;
$_SESSION['username']=$username;
$_SESSION['password']=$password;
echo "ok";
}else{
echo "Couldn't login.";
}
}else{
echo "Wrong username or password.";
}
}
Anyway, here is my java script code;
$(function(){
$("#loginbutton").click(function(){
var username = $("#username").val();
var password = $("#password").val();
if(username != "" && password != ""){
$.ajax("login.php",{
type : "POST",
data : "username="+username+"&password="+password,
success : function(data){
if(data == "ok"){
$("#message").html(data);
}else{
$("#fail").fadeIn();
}
}
});
}
});
});
Even though I put correct login information (when I get "ok" response from login.php, it always outputs $("#fail").fadeIn(); . instead of $("#message").html(data); I couldn't figure out where I am mistaken.
and here is login form:
<div id="login">
<form action="" onsubmit="return false;" method="post">
<input type="text" class="form-control" id="username" name="username" placeholder="Username" autocomplete="off"><br>
<input type="password" class="form-control" id="password" name="password" placeholder="Password" autocomplete="off"><br>
<input class="btn btn-success" type="submit" id="loginbutton" value="Login">
</form>
<div id="message"> </div>
<div id="fail" style="display: none;">failed.</div>
</div>
You are using type as post, but sending parameters as get.Change your ajax like this,
$.ajax("login.php",{
type : "POST",
data : {username:username,password:password},// only this line is changed.
success : function(data){
if(data == "ok"){
$("#message").html(data);
}else{
$("#fail").fadeIn();
}
}
});
Here is a quick example of using post with JQuery AJAX.
$(document).ready(function(){
$.post("login.php", {username:username, password:password}, function(data){
if(data == 'ok'){
$("#message").html(data);
}else{
alert(data);//alert the data you receive. It alerts you if there is any error in php file.
$("#fail").fadeIn();
}
});
});
Hope that was helpful!
Firstly, debug your code like this:
1) On button click you will put alert function inside javascript code. if it is working then move second step.
2) use alert function to print username and password if it comes inside your javascript code and correct as you put into input fields then move third step.
3) use serialize method in javascript.
I hope its help you to get your solution.

Login failed in my code after inserting proper login details (i.e username and password), code in php and jquery

I have following code (php and jquery) for Login for Student and Teacher (using same form for both access). In my system the admin can create Student and Teacher. Once created, the details are saved into database. The saved details is suppose to be use for login to their admin panel. But, the problem is , when Student or Teacher wants to login with the login details, provided by the admin (which has already been saved in database table), It display error message : Login Failed, Please check your username and password. (Same details, saved into database table is used for login process). This aching my head. If someone can tell me , if there is some error in my code, will be much appreciated.
login_form.php
<form id="login_form1" class="form-signin" method="post">
<h3 class="form-signin-heading"><i class="icon-lock"></i> Sign in</h3>
<input type="text" class="input-block-level" id="username" name="username" placeholder="Username" required>
<input type="password" class="input-block-level" id="password" name="password" placeholder="Password" required>
<button data-placement="right" title="Click Here to Sign In" id="signin" name="login" class="btn btn-info" type="submit"><i class="icon-signin icon-large"></i> Sign in</button>
<script type="text/javascript">
$(document).ready(function(){
$('#signin').tooltip('show');
$('#signin').tooltip('hide');
});
</script>
</form>
<script>
jQuery(document).ready(function(){
jQuery("#login_form1").submit(function(e){
e.preventDefault();
var formData = jQuery(this).serialize();
$.ajax({
type: "POST",
url: "login.php",
data: formData,
success: function(html){
if(html=='true_teacher') {
$.jGrowl("Loading File Please Wait......", { sticky: true });
$.jGrowl("Welcome to Soch College's E- Learning Management System", { header: 'Access Granted' });
var delay = 1000;
setTimeout(function(){ window.location = 'dasboard_teacher.php' }, delay);
} else if (html == 'true'){
$.jGrowl("Welcome to Soch College's E- Learning Management System", { header: 'Access Granted' });
var delay = 1000;
setTimeout(function(){ window.location = 'student_notification.php' }, delay);
} else {
$.jGrowl("Please Check your username and Password", { header: 'Login Failed' });
}
}
});
return false;
});
});
</script>
login.php
<?php include('admin/dbcon.php');
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
//for student login
$query_student = mysql_query("SELECT * FROM student WHERE username='$username' AND password='$password'");
$count_stu = mysql_num_rows($query_student);
$row_stu = mysql_fetch_array($query_student);
//for teacher login
$query_teacher = mysql_query("SELECT * FROM teacher WHERE username='$username' AND password='$password'")or die(mysql_error());
$count_tea = mysql_num_rows($query_teacher);
$row_tea = mysql_fetch_array($query_teacher);
if( $count_stu > 0 ) {
$_SESSION['id']=$row_student['student_id'];
echo 'true';
}else if( $count_tea > 0 ) {
$_SESSION['id']=$row_teacher['teacher_id'];
echo 'true_teacher';
}
else{
}?>
I think the problem is here;
if( $count_stu > 0 ) {
//$_SESSION['id']=$row_student['student_id'];// mistake
$_SESSION['id']=$row_stu['student_id'];
echo 'true';
}else if( $count_tea > 0 ) {
//$_SESSION['id']=$row_teacher['teacher_id'];// mistake
$_SESSION['id']=$row_tea['teacher_id'];
echo 'true_teacher';
}
else{
echo 'Wrong Username Or Password';
}
I agree with #Drew Pierce, you should consider using pdo or mysqli.
It is critical to use prepared statements when dealing directly with user supplied data from a webpage like username and password.
Your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements.
From Fred:
PHP Not Inserting Content in mySQL Database: Text, Images, Anything

Ajax login box doesn't call PHP file to continue process

The Ajax function for logging in and validating doesn't seem to get to the .php file for validation.
I'm new to both JS and Ajax and followed a few online tutorials, I then tried to implement this with what I had in place already and the problems started.
I've put an echo at the top of the page that Ajax calls, it never gets displayed. I've typed into url to be sure and it works fine. (displays the echo)
I've gone over the code a few times and can't see any obvious errors but then I'm not entirely certain of what I should be looking for.
If I leave the PHP in the 'header' of the HTML page it works fine but I understand this is bad practice. Grateful for any help.
HTML:
<form method="post" action="" id="ourLoginFormID_JS">
<div class="ourContactFormElement2">
<label for="username">Username:</label>
<input type="text" id="username" name="username" autocomplete="off" class="required" value="<?php if(isset($_POST['username'])) echo htmlentities($_POST['username']); ?>" />
</div>
<div class="ourContactFormElement2">
<label for="password">Password:</label>
<input type="password" id="password" name="password" autocomplete="off" class="required"/>
</div>
<div class="ourContactFormElement2">
<label> </label>
<input type="submit" name="loginButton" id="loginButton" value="Login!" onclick="validLogin()"/>
</div>
<div id="statusLogin"></div>
</form>
The Ajax:
function validLogin(){
$('.error').hide();
var username = $('#username').val();
if(username == ""){
$('label#usernameError').show();
$('input#username').focus();
return false;
}
$('.error').hide();
var password = $('#password').val();
if(password == ""){
$('label#passwordError').show();
$('input#password').focus();
return false;
}
var params = "username="+username+"&password="+password;
var url = "loginProcessAjax.php";
$("#statusLogin").show();
$("#statusLogin").fadeIn(400).html('<img src="image/loading.gif" />');
$.ajax({
type: 'POST',
url: url,
dataType: 'html',
data: params,
beforeSend: function() {
document.getElementById("statusLogin").innerHTML= 'checking...' ;
},
complete: function() {
},
success: function(html) {
$("#statusLogin").hide();
document.getElementById("statusLogin").innerHTML= html;
if(html=="success"){
window.location = "index.php"
}
}
});
}
PHP - I understand there may be some conflicting issues on this page but it doesn't get that far, however if you've any pointers that'd also be fantastic.
<?php
//check fields are filled in
echo "HULLOOOO!!!!!"; // doesn't display when run in function but ok from url
if(empty($_POST) === false){
$username = trim($_POST['username']);
$password = trim($_POST['password']);
//validate fields
if(empty($username) === true || empty($password) === true){
$errors[] = 'Your username and password are needed.';
}else if($users->userExists($username) === false){
$errors[] = 'That username does not exist';
}else if($users->emailActivated($username) === false){
$errors[] = 'You need to activate the account, please check your email.';
}else{
//start login
$login = $users->login($username, $password);
if($login === false){
$errors[] = 'That username or password is invalid';
//
// if(empty($errors) === false){
// echo '<p>' .implode('</p><p>', $errors).'</p>';
// }
}else{
//destroy old session and create new - prevents session fixation attacks
session_regenerate_id(true);
//all details are correct - the method returns the id to be sotred as a session
$_SESSION['id'] = $login;
//send user to their home page
echo "success";
header('Location: userHome.php');
exit();
}
}
}
Your data to the post request is not formatted in the right way. Use {'property1': 'value1', etc}.
First try to display the data with PHP, make it more complex when you're sure the connection between jQuery and PHP is working well.
Use Firebug or developer tools to see if there errors occur.

How to use a php ajax form in a color box?

I have a login form in (login.php). It call a separate sample.php via ajax, and sample.php returns it the value and the Javascript will show the relevant message depending on the php return value. It works perfectly fine in a normal webpage. But when I display the form in color box (in test.php). The javascript/jquery failed to run. I have research abit about this by using ajaxform, but how exactly do i do it? Please advise me some keywords for me to research further :(, i am stucked.
test.php:
$(".ajax").colorbox();
<a href="" class=ajax>Login</a>
This is my ajax function:
function login()
{
hideshow('loading',1);
error(0);
$.ajax({
type: "POST",
url: "http://utourpia.me/php/login_submit.php",
data: $('#loginForm').serialize(),
dataType: "json",
success: function(msg){
if(!(msg.status))
{
error(1,msg.txt);
}
else location.replace(msg.txt);
hideshow('loading',0);
}
});
}
This is my jQuery:
$('#loginForm').submit(function(e) {
login();
e.preventDefault();
});
This is my form:
<form id=loginForm method=post action="">
<label for=email class=email>Email:</label>
<input name=email type=text size=20 maxlength=40/>
<label for="password" class="password">Password:</label>
<input name="password" type="password" size="20" maxlength="40" />
<input class="login" type="submit" name="submit" value="Login" />
</form>
<div id="error"></div>
login_submit.php
<?php
require_once('../lib/connections/db.php');
include('../lib/functions/functions.php');
session_start();
$location_id = $_SESSION['location_id'];
$email = $_POST['email'];
$query = mysql_query('SELECT username FROM users WHERE email = "'.secureInput($email).'"') or die (mysql_error());
if(mysql_num_rows($query) == 1)
{
$row = mysql_fetch_assoc($query);
$username = $row['username'];
}
$returnURL1 = 'http://utourpia.me/php/places.php?id='.$location_id.'&username='.$username;
$returnURL2 = 'http://utourpia.me/php/myprofile.php?username='.$username;
$returnURL3 = 'http://utourpia.me';
$returnURL4 = 'http://utourpia.me/php/dreamtrip.php';
//For login
// we check if everything is filled in and perform checks
if(!$_POST['email'] || !$_POST['password'])
{
die(msg(0,"Email and / or password fields empty!"));
}
else
{
$res = login($_POST['email'],$_POST['password'],$username);
if ($res == 1){
die(msg(0,"Email and / or password incorrect!"));
}
if ($res == 2){
die(msg(0,"Sorry! Your account has been suspended!"));
}
if ($res == 3){
die(msg(0,"Sorry! Your account has not been activated. Please check your email's inbox or spam folder for a link to activate your account."));
}
if ($res == 99){
if ($_SESSION['login_submit']=="places.php")
{
echo(msg(1,$returnURL1));
}
else if ($_SESSION['login_submit']=="myprofile.php")
{
echo(msg(1,$returnURL2));
}
else if ($_SESSION['login_submit']=="home.php")
{
echo(msg(1,$returnURL3));
}
else if ($_SESSION['login_submit']=="dreamtrip.php")
{
echo(msg(1,$returnURL4));
}
}
}
function msg($status,$txt)
{
return '{"status":'.$status.',"txt":"'.$txt.'"}';
}
?>
First thing you need to change in the form tag:
Wright only above code. because you have given the method and URL that's why it refresh the page.
Replace your jquery code $('#loginForm').submit(function(e) { this code replace by $('.login').click(function(e) {.
Why are you using the replace method in the ajax success function is gives the error. remove else part.
location object does't have the replace method. if you want to redirect to user on success then use the location.href="your link";.
Make these changes and then check.

Check User Validation in MySql with javascript

i want check in my mysql database if the user enter the username and password correctly and then go in the home.html, i have some javascript code that detect when the user click the login button, but i can't understand how check in the database with javascript, i know how do that in php, but i can't understand how call the php from the javascript or do it directly in the js code, this is some code:
the form in the html:
<div id="password">
<div class="input username"><input type="text" placeholder="User name" /></div>
<div class="input password"><input type="password" placeholder="Password" /></div>
<button>Log in</button>
Back
</div>
</div>
then in my Login.js file i have this:
function forgot() {
//Se ho scritto la password allora fai l'animazione wobble, altrimenti vai in home.html
if($("#password .input.password input").attr("value")!='') {
$.notification(
{
title: "Wrong password",
content: "Just leave the password field empty to log in.",
icon: "!"
}
);
$("#password").removeClass().addClass("animated wobble").delay(1000).queue(function(){
$(this).removeClass();
$(this).clearQueue();
});
$("#password .input.password input").attr("value", "").focus();
} else {
document.location.href = "home.html";
}
}
now for the login i detect only if the field are empty, but i want detect mysql database how i can check it? because i want if the user enter wrong username and password span a $notification alert, anyone can help me?
Please suppose your html form is like below:
<input id="uname" name="uname" type="text" placeholder="User name" />
<input id="pass" name="pass" type="password" placeholder="Password" />
<button id="btn_login">Log in</button>
And suppose php script named checkPassword.php is like below:
<?php
/*
1.Retrieve post data : "uname" and "pass".
2.Cehck if user name and password is valid.
*/
if( /* valid user name and password */ ){
echo "OK";
}else{
echo "NG";
}
?>
The Javascript code could goes like below:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script language="javascript">
$(function() {
// set a event handler to the button
$("#btn_login").click(function() {
// retrieve form data
var uname = $("#uname").val();
var pass = $("#pass").val();
// send form data to the server side php script.
$.ajax({
type: "POST",
url: "checkPassword.php",
data: { uname:uname, pass:pass }
}).done(function( data ) {
// Now the output from PHP is set to 'data'.
// Check if the 'data' contains 'OK' or 'NG'
if (data.indexOf("OK") >= 0){
// you can do something here
alert("Login Successed.");
location.href = "ok.html";
}else if(data.indexOf("NG") >= 0){
// you can do something here
alert("Login Faild.");
location.href = "ng.html";
}
});
});
});
</script>
You can't communicate directly from client side JS to a server side database.
To make an HTTP request (to a server side program), use the XMLHttpRequest object.
if(document.pressed=='SUBMIT')
{
var uname = document.getElementById('uname').value;
if(uname.trim()=='' || uname.trim()==null)
{
alert("<?php echo 'uname_null'?>");
return false;
}
}
you can do the validation part on the sql server side if you use stored procedures

Categories