passing variable back from php to jquery? - php

I am trying to convert my login page to use html and use jquery and php to fetch and process the results, Reason is if i want to go mobile with my project then i am nearly there.
The problem i have is passing variables back from php to jquery to display at the same time.
my example
index.html
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Auth Demo 2</title>
<script src="jquery/jquery-1.7.2.min.js"></script>
<script src="main.js"></script>
</head>
<body onload="handleLogin()">
<form id="loginForm">
<label for="email">Email:</label>
<input type="text" name="email" id="email" value="" placeholder="email" />
<label for="password">Password:</label>
<input type="password" name="password" id="password" value="" placeholder="Password" />
<input type="submit" value="Login" id="submitButton">
</form>
</body>
</html>
main.js
function handleLogin(){
var form = $("#loginForm");
var u = $("#email", form).val();
var p = $("#password", form).val();
if(u!= '' && p!= '') {
$.post("http://www.mysite.co.uk/login.php",{
email:$('#email', form).val(),
password:$('#password', form).val(),
rand:Math.random()
} ,function(data)
{
if(data=='yes') //if correct login detail
{
alert( "Request success: ");
}
else
{
//add reason in alert box here
alert ("failed reason")
}
});
} else {
alert( "Username/password empty");
}
return false;//not to post the form physically
}
login.php
<?//get the posted values
require_once("../backend/functions.php");
dbconn(true);
if ($_POST["email"] && $_POST["password"]) {
$password = passhash($_POST["password"]);
if (!empty($_POST["email"]) && !empty($_POST["password"])) {
$res = SQL_Query_exec("SELECT id, password, secret, status, enabled FROM users WHERE email = " . sqlesc($_POST["email"]) . "");
$row = mysql_fetch_assoc($res);
if ( ! $row || $row["password"] != $password )
$message = "Wrong password";
elseif ($row["status"] == "pending")
$message = "Account Pending";
elseif ($row["enabled"] == "no")
$message = "Account Suspened";
} else
$message = "No Username/password added";
if (!$message){
logincookie($row["id"], $row["password"], $row["secret"]);
if (!empty($_POST["returnto"])) {
header("Refresh: 0; url=" . $_POST["returnto"]);
die();
}
else {
echo "yes";
die();
}
}else{
echo $message;
}
}
logoutcookie();
As you can see when the login fails have various reasons i want to pass back to the alert box. Whats the best way to go about this

just alert data
if(data=='yes') //if correct login detail
{
alert( "Request success: ");
}
else{
alert (data)
}
however i recommmend to get the response as JSON.....
if(u!= '' && p!= '') {
$.post("http://www.mysite.co.uk/login.php",{
email:$('#email', form).val(),
password:$('#password', form).val(),
rand:Math.random()
} ,function(data)
{
if(data=='yes') //if correct login detail
{
alert( "Request success: ");
}
else
{ //add reason in alert box here
alert (data)
}
});
} else {
alert( "Username/password empty");
}
return false;//not to post the form physically
}

Try to use JSON;
JSON.stringify(your_object, null, 2);
Catch the POST in PHP with this to get an array back: http://www.php.net/manual/en/function.json-decode.php
$data = json_decode($_POST);
When PHP is done echo a encoded JSON string of your array data back: http://www.php.net/manual/en/function.json-encode.php
echo json_encode($return_data);
In jQuery, for testing do;
console.log(data);
console.log(data.yes);

The best way to do this is to use $.ajax() and use the "XML" type. Then have login.php return a XML file with whatever parameters you need (user id, error message if any, username, etc). You can then parse the XML file with jQuery to use those variables immediately. It's more secure to handle errors on the backend anyway.

function handleLogin(){
var form = $("#loginForm");
var u = $("#email", form).val();
var p = $("#password", form).val();
if(u!= '' && p!= '') {
jQuery.ajax({
type: "POST",
url: "http://www.mysite.co.uk/login.php",
data: 'username='+u+'&password='+p+'&rand='+Math.random(),
complete: function(data){
if(data.responseText == 'yes'){
alert( "Request success: ");
}else{
alert( "failed: ");
}
});
} else {
alert( "Username/password empty");
}
return false;//not to post the form physically
}

Related

How to remove HTML tags from ajax response using PHP?

I need to check from the database if email exists or not by using Ajax. I am getting a response, but coming with some HTML content. I have given below my code what I have followed.
My Ajax code:
var username_state = false;
var email_state = false;
$('#username').on('blur', function(){
var username = $('#username').val();
if (username == '') {
username_state = false;
return;
}
$.ajax({
url: 'user_list.php',
type: 'post',
data: {
'username_check' : 1,
'user_name' : username,
},
success: function(response){
$("html").html($("html", response).html());
if (response == 'taken' ) {
response.find(element).remove();
alert('hi');
username_state = false;
$('#username').parent().removeClass();
$('#username').parent().addClass("form_error");
$('#username').siblings("span").text('Sorry... Username already taken');
}
else if (response == 'not_taken') {
username_state = true;
$('#username').parent().removeClass();
$('#username').parent().addClass("form_success");
$('#username').siblings("span").text('Username available');
}
}
});
});
My php Code
$db = mysqli_connect('localhost', 'root', '', 'my_assesment');
if (isset($_POST['username_check'])) {
$username = $_POST['user_name'];
// echo $username;
$sql = "SELECT * FROM user_information
WHERE user_name='".$_POST["user_name"]."'";
//echo $sql;
$results = mysqli_query($db, $sql);
if (mysqli_num_rows($results) > 0) {
//$response = true;
echo "taken";
}else{
$response = false;
echo 'not_taken';
}
This is am getting response
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<!-- jQuery -->
not_taken
Looking at the output you are receiving my guess is that the ajax request is being sent to the same page. If that is the case then initially wrap the entire username checking code within a suitable if test and ensure that any HTML buffer content is disposed of completely before sending the response to the ajax callback.
/*
Test that the request is a POST request and that
the variables you are expecting have been sent.
As you are using data sent by the client you MUST
take precautions to mitigate SQL injection attacks.
Use a Prepared statement rather than directly embedding
user supplied data in the SQL.
*/
if( $_SERVER['REQUEST_METHOD']=='POST' && isset(
$_POST['username_check'],
$_POST['user_name']
)){
$db = mysqli_connect('localhost', 'root', '', 'my_assesment');
$sql='SELECT `user_name` FROM `user_information` WHERE `user_name`=?';
$stmt=$db->prepare( $sql );
$stmt->bind_param('s',$_POST['user_name']);
$stmt->execute();
$stmt->store_result();
$rows=$stmt->num_rows;
$stmt->close();
$response=( $rows > 0 ) ? 'taken' : 'not_taken';
# flush buffer to remove any other HTML / text content
ob_clean();
#exit completely from this logic branch
exit( $response );
}
The test page I used to try to figure out the fault in the callback was exactly as follows. Essentially rather than respecting the checkbox to do a test and querying the db a random integer determines if the status is taken or not_taken simply to test the logic in the callback.
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset(
$_POST['username_check'],
$_POST['user_name']
)){
/*
$db = mysqli_connect('localhost', 'root', '', 'my_assesment');
$sql='SELECT `user_name` FROM `user_information` WHERE `user_name`=?';
$stmt=$db->prepare( $sql );
$stmt->bind_param('s',$_POST['user_name']);
$stmt->execute();
$stmt->store_result();
$rows=$stmt->num_rows;
$stmt->close();
*/
$rows=mt_rand(0,1);
$response=( $rows > 0 ) ? 'taken' : 'not_taken';
ob_clean();
exit( $response );
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>?Username Check Test Page</title>
<script src='//code.jquery.com/jquery-latest.js'></script>
<style>
label{display:block;padding:1rem;}
.form_success{background:rgba(0,255,0,0.25)!important;}
.form_error{background:rgba(255,0,0,0.25)!important;)}
</style>
</head>
<body>
<form name='usercheck'>
<label>Username:<input type='text' id='username' name='user_name' value='geronimo' /></label>
<label>Username Check:<input type='checkbox' name='username_check' value=1 /></label>
</form>
<script>
var username_state = false;
var email_state = false;
$('#username').on('blur', function(){
var username = $('#username').val();
if (username == '') {
username_state = false;
return;
}
$.ajax({
url: location.href, // 'user_list.php' ~ same page here!
type: 'post',
data: {
'username_check' : 1,
'user_name' : username,
},
success: function(response){
alert(response);
// no idea what this is doing
// $("html").html($("html", response).html());
if (response == 'taken' ) {
// this caused issues for me... no error as such but prevented further processing
// response.find(element).remove();
alert('hi - choose another username');
username_state = false;
$('#username').parent().removeClass();
$('#username').parent().addClass("form_error");
$('#username').siblings("span").text('Sorry... Username already taken');
}
else if (response == 'not_taken') {
username_state = true;
alert('ok - that user name is fine');
$('#username').parent().removeClass();
$('#username').parent().addClass("form_success");
$('#username').siblings("span").text('Username available');
}
}
});
});
</script>
</body>
</html>

Not redirecting to another page after successful ajax request complete

I am validating a sign In form through ajax. After successful validation the form is not redirecting to the required page.
Ajax Codes
function login_submit(){
var stat="";
$("#submit").val("Loging in...");
$.ajax({
type: "POST",
url: "php/login.php",
data: {
uname: $("#uname").val(),
pass : $("#pass").val()
},
success: function(result) {
if(result=="parent"){
window.location = "http://localhost:90/auction/augeo/admin/parent_admin/index";
}
else if(result == "sucess_normal"){
window.location.assign("../normal_admin");
}
else if(result == "deactivated account") {
window.location.assign("reactivate_account/");
}
else if(result == "banned account") {
window.location.assign("banned_account/");
}
else{
$("#submit").val("Login");
$("#error_msg").css({color: 'red'});
document.getElementById("error_msg").innerHTML= result;
stat = false;
}
}
});
if(!stat)
return false;
}
The php code
if(isset($_POST['uname']) && isset($_POST['pass'])){
$username = encode($_POST['uname']);
$password = encrypt(encode($_POST['pass']));
// check if entered username and password is in the database
$result = mysqli_query($conn,"SELECT * From admin_account where admin_account.username = '$username' AND admin_account.password = '$password' ");
if($row = mysqli_num_rows($result) == 1){
$found = mysqli_fetch_array($result);
if($found['state'] == 1){
$account_id = $found['account_id'];
setcookie("admin_id", $account_id, time() + (86400 * 30), "/");
$_SESSION['admin_id'] = $account_id;
$result1 = mysqli_query($conn,"SELECT role_id From admin where admin_id = '$account_id'");
$found1 = mysqli_fetch_array($result1);
$_SESSION['account_type'] = $found1['role_id'];
if($found1['role_id'] == "1"){
echo "parent";
//header("Location: http://localhost:90/auction/augeo/admin/parent_admin/index");
}else{
echo "sucess_normal";
}
}
elseif($found['state'] == 2){
echo "banned account";
}
else{
$_SESSION['deactivated_id'] = $found['account_id'];
echo "deactivated account";
}
}
else{
echo "Incorrect Username or Password";
}
}
I have tried all I could do but to no avail. I want to check if result=="parent" and if result=="parent" it should redirect to window.location = "http://localhost:90/auction/augeo/admin/parent_admin/index"; but instead it is echoing out parent.
You say "it is echoing out parent". But this should never happen with the AJAX code you supplied.
So I'm suspecting that you have a form that's running its own default submit, and that is what you're seeing.
You may want to check out this answer:
$('#idOfYourForm').submit(function() {
var $theForm = $(this);
// This is a button or field, right? NOT the form.
$("#submit").val("Logging in...");
$.post(
'php/login.php',
{
uname: $("#uname").val(),
pass : $("#pass").val()
}
).done(function(result) {
// check the result
alert("Server said: " + result);
});
// prevent submitting again
return false;
});
You get the button with
$("#submit")
This is ok, but if the button is defined as:
<input type="submit" id="submit" value="..." />
You'll get a subsequent submit of the form the button is defined in.
To avoid this, a far easier solution to the other suggested, is to not use a submit button at all. Instead, use a simple action button. These are two examples, the second of which is probably better because it is easier to design with bootstrap/HTML5/CSS...
<input type="button" id="submit" value="..." />
or better:
<button type="button" id="submit">...</button>
In case of slow server/network, you'll probably want to aid AJAX usability by disabling the button:
$("#submit").val("Logging in...").prop("disable", "disable");
This helps avoiding multiple submits when the server is slow and the user impatient.

How to enter CSRF on ajax?

I have this code
---------- index.php ----------
<script>
function validLogin() {
var email=$('#memail').val();
var testEmail = /^[A-Z0-9._%+-]+#([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
var password=$('#mpass').val();
var dataString = email='+ email + '&password='+ password;
$.ajax({
type: "POST",
url: "processed.php",
data: dataString,
cache: false,
success: function(result){
var result=trim(result);
if(result=='correct'){
window.location='/';
} else {
}
}
});
return true;
}
function trim(str){
var str=str.replace(/^\s+|\s+$/,'');
return str;
}
</script>
<div class="login">
<div class="input-group">
<input type="text" id="memail" value="" placeholder="Email" class="memail">
</div>
<div class="input-group">
<input type="password" id="mpass" value="" placeholder="Password" class="mpassword">
</div>
<div class="checkout-submit-section">
<div class="payment-submit">
<div class="order-submit">
<button id="msubmit" type="submit" name="submit_button" class="greenx" style="margin-top:-20px;" onclick="validLogin()">
Login
</button>
</div>
</div>
</div>
</div>
and
------ processed.php ---------
<?php
session_start();
include_once('../db/ds.php');
$message=array();
if(isset($_POST['email']) && !empty($_POST['email'])){
$email = $mysqli->real_escape_string($_POST['email']);
$email= htmlentities($email);
}else{
$message[]='email';
}
if(isset($_POST['password']) && !empty($_POST['password'])){
$password = $mysqli->real_escape_string($_POST['password']);
$password= htmlentities($password);
}else{
$message[]='password';
}
$countError=count($message);
if($countError > 0){
for($i=0;$i<$countError;$i++){
}
}else{
$password=md5($password);
$query = "select * from user where email='$email' and password='$password'";
$res = $mysqli->query($query);
$checkUser = $res->num_rows;
if($checkUser > 0){
$lol = $res->fetch_array(MYSQLI_BOTH);
$iduser = $lol['id'];
$_SESSION['status']=true;
$_SESSION['id']=$iduser;
echo 'correct';
}else{
}
}
}
?>
maybe this code for CSRF, but I do not know how to use them
function createToken()
{
$token= base64_encode( openssl_random_pseudo_bytes(32));
$_SESSION['csrfvalue']=$token;
return $token;
}
function unsetToken()
{
unset($_SESSION['csrfvalue']);
}
function validation()
{
$csrfvalue = isset($_SESSION['csrfvalue']) ? mysql_real_escape_string($_SESSION['csrfvalue']) : '';
if(isset($_POST['csrf_name']))
{
$value_input=$_POST['csrf_name'];
if($value_input==$csrfvalue)
{
unsetToken();
return true;
}else{
unsetToken();
return false;
}
}else{
unsetToken();
return false;
}
}
<input type="hidden" name="csrf_name" value="<?php echo createToken();?>"/>
How to use CSRF without input <form action="" method="post">? Because when I test the security of this code, this code dangerous if not using CSRF.
I've been looking for to several sites , but they all use input form.
1.How to use CSRF in the above code ?
Whether my code is too simple? and could be tricked ? How do I secure it ?
If i use ajax , Whether I have to use CSRF ?
EDIT
--------------- processed.php ----------------
<?php
require '../../db/sessions.php';
require '../../db/ds.php';
require '../../db/error.php';
$user=$row['id'];
$message=array();
if(isset($_POST['emailx']) && !empty($_POST['emailx'])){
$emailx = $mysqli->real_escape_string($_POST['emailx']);
$emailx= htmlentities($emailx);
}else{
$message[]='email';
}
if(isset($_POST['hpx']) && !empty($_POST['hpx'])){
$hpx = $mysqli->real_escape_string($_POST['hpx']);
$hpx= htmlentities($hpx);
}else{
$message[]='hp';
}
if(isset($_POST['namax']) && !empty($_POST['namax'])){
$namax = $mysqli->real_escape_string($_POST['namax']);
$namax= htmlentities($namax);
}else{
$message[]='nama';
}
if(isset($_POST['token']) && !empty($_POST['token'])){
$tokens = $mysqli->real_escape_string($_POST['token']);
}else{
$message[]='email';
}
$countError=count($message);
if($countError > 0){
for($i=0;$i<$countError;$i++){
}
}else{
if(validation($tokens, $crsfa)==true) {
$query = "UPDATE user SET email='$emailx', nama='$namax', hp='$hpx' WHERE id='$user'";
$res = $mysqli->query($query);
echo 'OKS';
}else{
echo "Null";
return false;
}
}
?>
--------------- index.php ----------------
<meta name="csrf_token" content="<?php echo createToken();?>">
.
.
.
.
.
<script>
function validUbah() {
var hpx=$('#hp').val();
var emailx=$('#email').val();
var namax=$('#nama').val();
var token=$('[name="csrf_token"]').attr('content');
var dataString = 'hpx='+ hpx + '&emailx='+ emailx + '&namax='+ namax + '&token='+ token;
$.ajax({
type: "POST",
url: "processed.php",
data: dataString,
success: function(result){
var result=trim(result);
if(result=='OKS'){
$(".spinner").hide();
$(".spanlogin").show();
$(".spanlogin").html('Berhasil');
$(".nm7").html(namax);
} else {
$(".spinner").hide();
$(".spanlogin").show();
$(".spanlogin").html(result);
return false;
}
}
});
return true;
}
function trim(str){
var str=str.replace(/^\s+|\s+$/,'');
return str;
}
</script>
--------------- sessions.php ---------------------
function unsetToken()
{
unset($crsfa);
createToken();
}
function validation($varians, $crsfa)
{
$csrfvalue = isset($crsfa);
if(isset($varians))
{
$value_input=$varians;
if($value_input==$csrfvalue)
{
unsetToken();
return true;
}else{
unsetToken();
return false;
}
}else{
unsetToken();
return false;
}
}
$crsfa=$_SESSION['csrfvalue'];
if you are implementing anti-CSRF techniques, you should use the token on every post/ajax request.
Maybe you can implement your token as meta-Tag:
<meta name="csrf-token" content="MERvRHE0MmVHcSU9OEUfPHs3JSALZQpcAC1ccBVcZA14KVlxN35xHQ==">
Whatever you do, do NOT use MD5 for hashing passwords.
Use PHP's crypt() or other means for password storage.
Cheers

Can't figure out what I'm doing wrong with this php conditional

I'm trying to do a really simple login system using php. I have two files at the moment: index.php and verifyCredentials.php
index.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test Site</title>
</head>
<body>
<h1>Welcome to My Test Homepage!</h1>
<?php if ($_SESSION['logged_in'] != "true") : ?>
<form method="post" action="verifyCredentials.php">
Username: <input type="text" name="username" value=""/><br>
Password: <input type="password" name="password" value=""/><br>
<input type="submit" name="submit" value="Submit"/><br>
</form>
<?php else : ?>
<h2>You're logged in! :)</h2>
<?php endif ?>
<?php if($_GET['verferr']==1){echo "<b>Login failed: incorrect username or password.</b>";} ?>
</body>
</html>
verifyCredentials.php
<?php
$username = $_POST['username'];
$password = $_POST['password'];
if($username == "myusername" && $password == "letmein")
{
$_SESSION['logged_in'] = "true";
header("Location: index.php");
exit;
}
else
{
$loginfailed_param = "?verferr=1";
header("Location: index.php" . $loginfailed_param);
exit;
}
?>
I've successfully made it so that if your username/password were incorrect (i.e. not equal to myusername and letmein), then it redirects to the login page and echo's an error message under the form.
I'm trying to make it so that when they do verify that the form on index.php, the form disappears and is replaced with some success text. But, when I type in myusername and letmein, it just redirects to the login without an error and the form still showing.
From the research I've done, I'm required to use the if-else php structure as shown in my index.php file if I want to have html in between my php nodes, but am I doing this incorrectly?
Can anyone tell what I am doing wrong here?
PHP Sessions require that you call session_start() at the top of every page where you use $_SESSION. I don't see it in your example.
If you are going to use sessions to store data make sure you have session_start(); at the top of every page you call. Otherwise it won't read in the session identifier and will assume you want to start a new one.
So at the top of your index.php and verifyCredentials.php add the command. But make sure you have it as the first line of code on the page. You will then need to add it to any page that is directly requested.
For example, if you have index.php and it includes form.php and nav.php, then only index.php will need the session_start(), but if you have a link to form_processing.php, then form_processing.php will need to have session_start() as well.
Aww, you accepted right as I had this ready. :(
Here is what you need to use. anyway..
(Also, you should use jQuery for better transitional effects, see below)
<?php
session_start();
$args = array(
'username' => FILTER_SANITIZE_SPECIAL_CHARS,
'password' => FILTER_SANITIZE_SPECIAL_CHARS);
$post = filter_input_array(INPUT_POST, $args);
if ($post) {
$username = $post['username'];
$password = $post['password'];
if($username == "myusername" && $password == "letmein") {
$_SESSION['logged_in'] = true;
header("Location: index.php");
exit;
} else {
$loginfailed_param = "?verferr=1";
header("Location: index.php" . $loginfailed_param);
exit;
}
}
if ($_SESSION['logged_in'] === true) {
//User has logged in
}
?>
Using jQuery
HTML
<div id="loginForm">
<form id="myLoginForm">
<input id="username">
<input id="password">
<button id="formSubmit" name="formSubmit">Submit Form</button>
<input style="display: none;" type="text" id="realSubmit" name="realSubmit" value="hidden">
</form>
</div>
<div id="successPage">
Thank you for loggging in...
</div>
<div id="loginHome">
Login Homepage
Welcome <span id="displayUsername"></span>
</div>
jQuery
(function($){
$(function(){
$("#formSubmit").on('click', function() {
var username= $("#username").val();
var password = $("#password").val();
var data = {username: username, password: password};
delegateAjax('../myAjax.php', data, 'POST');
});
});
function delegateAjax(url, data, responseType, dataType, callback) {
function successHandler(data) {
console.log("Ajax Success");
var responseData = $.parseJSON(data);
if (responseData.status === 'Success') {
$("#loginForm").fadeOut(1500, function() {
$("#successPage").fadeIn(1500, function() {
$(this).fadeOut(1500, function() {
$("#displayUsername").html(responseData.username);
$("#loginHome").fadeIn(1500);
});
});
});
}
};
function failureHandler(xhr, status, error) {
console.log("Ajax Error");
console.log(status);
console.log(error);
console.dir(xhr);
};
function handler404(xhr, status, error) {
console.log("404 Error");
console.log(status);
console.log(error);
console.dir(xhr);
};
function handler500(xhr, status, error) {
console.log("500 Error");
console.log(status);
console.log(error);
console.dir(xhr);
};
url = typeof url !== 'undefined' ? url : 'js/ajaxDefault.php';
data = typeof data !== 'undefined' ? data : new Object();
responseType = typeof responseType !== 'undefined' ? responseType : 'GET';
dataType = typeof dataType !== 'undefined' ? dataType : 'json';
callback = typeof callback !== 'undefined' ? callback : 'callback';
var jqxhr = $.ajax({url: url, type: responseType, cache: true, data: data, dataType: dataType, jsonp: callback,
statusCode: { 404: handler404, 500: handler500 }});
jqxhr.done(successHandler);
jqxhr.fail(failureHandler);
};
})(jQuery);
PHP
myAjax.php
<?php
define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
if (!IS_AJAX) {
$response['status'] = 'Error';
$response['message'] = 'Same Origin Policy Error';
echo json_encode($response);
exit;
}
$pos = strpos($_SERVER['HTTP_REFERER'], getenv('HTTP_HOST'));
if ($pos === false) {
$response['status'] = 'Error';
$response['message'] = 'Same Origin Policy Error';
echo json_encode($response);
exit;
}
function validUser($data) {
//connect to db and validate user
$dbi = new mysqliObject();
$params['string'] = $data['username'];
$dbi->newSelect($params);
$table = 'users';
$select = '*';
$where = '`username` = ? LIMIT 1';
if ($dbi->exec($table, $select, $where)) {
$result = $dbi->result[0];
return passwordVerify($result['password']); //true/false
} else {
//for debugging
//echo 'Last Error: '.$dbi->get('lastError').'<br>'."\r\n";
//echo 'Last Query: '.$dbi->get('lastQuery').'<br>'."\r\n";
return false;
}
}
$args = array(
'username' => FILTER_SANITIZE_SPECIAL_CHARS,
'password' => FILTER_SANITIZE_SPECIAL_CHARS);
$post = filter_input_array(INPUT_POST, $args);
if ($post) {
if (validUser($post)) {
$response['status'] = 'success';
$response['username'] = $username;
echo json_encode($response);
exit;
} else {
$response['status'] = 'Failed';
$response['message'] = 'Username/Password Invalid';
echo json_encode($response);
exit;
}
}
$response['status'] = 'Error';
$response['message'] = 'POST Data Invalid';
echo json_encode($response);
exit;

Authenicating user using jQuery AJAX not working

I'm trying to authenticate a user using AJAX wrapped with jQuery to call a PHP script that queries a MySQL database. I'm NOT familiar with any of those technologies but I (sorta) managed to get them working individually, but I can't get the jQuery, AJAX and HTML to work properly.
[Edit:] I followed Trinh Hoang Nhu's advice and added a return false; statement to disable the Submit button. All previous errors fixed, I can't get the object returned by the AJAX right.
HTML
Here's the HTML snippet I use:
<form id="form" method='post'>
<label>Username:</label>
<input id="user" name="user" type="text" maxlength="30" required /> <br />
<label>Password:</label>
<input id="pass" name="pass" type="password" maxlength="30" required /> <br />
<input id="url" name="url" type="text" value="<?php echo $_GET['url'] ?>" hidden />
<input name="submit" type="submit" value="I'm done">
</form>
jQuery/AJAX
Here's my jquery code for using AJAX to authenticate a user (sorry if the indenting is messed up because of the tabs):
function changeMessage(message) {
document.getElementById("message").innerHTML = message; }
$(document).ready(function() {
$("#form").submit(function() {
changeMessage("Checking");
//check the username exists or not from ajax
$.post("/stufftothink/php/AJAX/login.php",
{user: $("#user").val(), pass: $("#pass").val(), url: $("#url") },
function(result) {
//if failed
if (result === 'false') {
changeMessage("Invalid username or password. Check for typos and try again");
$("#pass").val(""); }
//if authenticated
else {
changeMessage("Authenticated");
window.location.href = result; }
} );
//to disable the submit button
return false;
} );
} )
PHP
And here's my PHP script that gets called:
<?php
ob_start();
session_start();
$user = $_POST['user'];
$pass = md5($_POST['pass']);
mysql_connect('localhost', 'root', '');
mysql_select_db('stufftothink');
$query = "select * from users where user = '$user' and pass = '$pass'";
$result = mysql_query($query);
$i = 0;
while ($row = mysql_fetch_array($result)) {
$i = 1; }
if ($i == 1) {
$_SESSION['user'] = $user;
$invalid_urls = array('register.php', 'login.php');
$url = $_REQUEST['url']; //not sure whether _GET or _POST
if (in_array($url, $invalid_urls)) {
echo '/stufftothink/profile.php'; }
else {
echo '/stufftothink/'.$url; }
}
else {
echo 'false'; }
mysql_close();
?>
Edit
I've been getting a lot of downvotes on this question. I had accidentally submitted the question without the explanation filled in. I went back to edit it, but when I came back, there were already 4 downvotes. It had barely been a couple of minutes. Am I doing something wrong, or were the first 5 minutes the problem?
First if you want to submit form using ajax, you must return false from your submit function. Otherwise your browser will handle it and redirect you to another page.
If you want to return an object from PHP, you must convert it to json using json_encode,
for example:
//PHP
$return = array("url" => "http://www.google.com");
echo json_encode($return);
//would echo something like {"url":"http://www.google.com"}
//JS
$.post(url, data, function(data){
alert(data.url);
});
You have no ending ;'s on functions.
Should be:
function changeMessage(message) {
document.getElementById("message").innerHTML = message;
};
$(document).ready(function() {
$("#form").submit(function() {
changeMessage("Checking");
//check the username exists or not from ajax
$.post("/stufftothink/php/AJAX/login.php",
{user: $("#user").val(), pass:$("#pass").val() },
function(result) {
//if failed
if (result === 'false') {
changeMessage("Invalid username or password. Check for typos and try again");
$("#pass").val("");
}
//if authenticated
else {
changeMessage("Authenticatred");
window.location.href = "/stufftothink/" + result;
}
});
});
});
Not sure if that'll fix it, but it's the only thing that jumps out at me.

Categories