PHP Session ID Variable Returned With AJAX - php

I'm working on an AJAX login system and am not sure how to return the PHP session variable from AJAX unto the login page. My question is, how do I return the php variable unto the login page, if that is even possible. Below is the sample I created.
Login Page
<?php
session_start();
?>
<form>
<input type="text" id="username" />
<input type="text" id="password"/>
<input type="button" id="submit" />
</form>
<script type="text/javascript" >
$('#submit').click(function() {
var username = $('#username').val();
var password = $('#password').val();
$.post('ajax_file.php',
{
username: username,
password:password,
},
function (data) {
/* what do I do here that will return the php variable
$_SESSION['user_id'] and let the user be logged in when
they go to homepage.php*/
setTimeout('window.location.href="homepage.php"', 2000);
});});
</script>
Here is the ajax page. I understand that the logic doesn't make sense for the session variable to pop out of nowhere, let's just assume that is was created earlier in the page.
$username = $_POST['username'];
$password = $_POST['password'];
if(login($username, $password)) {
return $session_user_id = $_SESSION['user_id'];
}

You can just do the AJAX post, set the session variable to the session in the page receiving the post, and it will be stored in the session (it's the same session). In the AJAX callback forward the user to the home page.
Of course you must consider the scenario that the login credentials are incorrect.

The trick is that your JavaScript doesn't even have to know about sessions at all; you can configure PHP to use HttpOnly cookies for its session management via the respective ini setting.
I would implement the AJAX script like this:
session_start(); // start the session
if (login($username, $password)) {
// alter session to hold user id
$_SESSION'user_id'] = $user_id_from_database_or_something;
return true;
} else {
return false;
}
The AJAX complete handler looks at the return value and redirect to the homepage if it was true. Something like below (I'm assuming that the PHP return is translated into something like echo json_encode($return_value):
if (data) {
// do redirect
} else {
// login failed
}
Then, when the user comes to the homepage their browser would send a session cookie so you can determine if they're logged in.

Improving the Answer
FOr Jquery, USe function below
function sendAjax(showAllExist, controller)
{
$.ajax({
type: "post",
url: login.php,
data: yourformdatacomeshere,
beforeSend: function() {
//do whatever you want to do before request
},
error: function() {
//display in case of error
},
success: function(data) {
//display in case of error
if(data!=""){
//redirect use to home pahe
window.location.href ='homepage.php';
}else{
//display login is not correct
}
},
complete: function() {
//hide any event which you have started on beforeSend
}
});
return true;
}

Cant you just do this:
$.post('ajax_file.php',
{
username: username,
password:password,
loginSession: <?php echo $_SESSION['user_id']; ?>
},
function (data) {
//Check here if login is correct.
if correct, create this variable:
var logged= "?logged="+data.SessionID;
/* what do I do here that will return the php variable
$_SESSION['user_id'] and let the user be logged in when
they go to homepage.php*/
setTimeout('window.location.href="homepage.php"+logged+"'", 2000);
});})
When data comes back go the homepage.php with a sessionID.
on the php script do this:
if(isset($_GET['logged'])){
start_session();
$_Session['LOGGED']='true';
}

use this method which is improvised above shail answer.
your ajax file code
$username = $_POST['username'];
$password = $_POST['password'];
if(login($username, $password)) {
$session_user_id = $_SESSION['user_id'];// this is from your code
$responseArray = array("message"=>"success","sessionId"=>$session_user_id);
}
else
{
$session_user_id = "";
$responseArray = array("message"=>"error","sessionId"=>$session_user_id);
}
echo json_encode ( $responseArray );
die ();
then in ajax function make below changes.
var frmdata = jQuery("#logindata").serialize(); // which contains the data of username and password
jQuery.ajax({
type : "POST"
,url :'ajax_file.php'
,data :frmdata
,dataType: "json"
,success : function(data){
if(data.message == "success")
{
//redirect it to your desire page
}
else
{
//redirect it to your login page
}
}
,beforeSend: function(html){
// some loader goes here while ajax is processing.
}
});
hope this help feel free to ask anything for this answer.

Related

Code technique - jquery login with php server

It is my 2nd day developing mobile app. And for now I'm dealing with login credentials.
I'm using Intel XDK. I have an idea/logic on how the login page will work. But at some point, I'm new to jquery ajax method. What I would like to accomplish is how to successfully implement it with existing server(website).
This is the submit button code.
$(document).on("click", "#login", function(evt)
{
var email=$("#input_email").val();
var password=$("#input_password").val();
var user_data = 'email='+email+'&password='+password;
if($.trim(email).length>0 && $.trim(password).length>0) {
$.ajax({
type: "POST",
url: "www.mysite.com/app/login_user.php",
crossDomain: true,
dataType: 'json',
data: user_data,
beforeSend: function(){
$(#loader).css({display: "block" });
},
success : function(data){
$(#loader).css({display: "none"});
alert(data);},
error : function(httpReq,status,exception){
alert(status+" "+exception);
}
});
}
return false;
});
And This is my code on php server-side.
<?php
header("Content-Type: application/json");
header('Access-Control-Allow-Origin: *'); //newly added
include('../config.php');
session_start();
if(isset($_GET['email']) && isset($_GET['password'])){
$get = $_GET;
array_walk_recursive($get, 'clean');
$sql = "SELECT * FROM user WHERE //some condition here ";
$user = db::select_row($sql);
$access = 'true password';//should logged in the user, and landed to home page.
if($user['user_status'] == 'active' || $user['user_status'] == 'new' || $user['user_status'] == 'not active'){
$_SESSION['user_id'] = $user['user_id'];
$_SESSION['user_email'] = $user['user_email'];
$_SESSION['user_fullname'] = $user['user_fullname'];
}elseif($user){
$access = 'Account is deactivated!'; //Show as popup message
}else{
$access = 'Username and password didn\'t match.'; //Show as popup message
}
echo json_encode($access); //newly added
}
////////Conditional code to be added here base on $access value.
////////Send result to mobile app and respond.
////////Need some help.
?>
I hope you understand my needs. All ideas for improvement is greatly appreciated.
Edited#1: I added some line of code to my php server and some additional code to my jquery code. It is working now, it is alerting the data $access.
Question#1: How can I use the server response(e.g "$access value" is = 'true password' or 'Username and password didn't match.') to make some action on the client-side?

How to redirect user on successful ajax call? Otherwise display error message in form

Updated:
Thanks for reading - My login form calls on login.php to check whether the user has entered a registered email address or not. If the address is registered, it echoes back "redirect", if it is not registered, it echoes "Email not registered". My current code only redirects to mydomain.com/# since the form action is set to #, because I'm using the ajax to submit the form.
How do I:
Redirect the user to page private.php if the php has echoed "redirect" - otherwise how do I display "Email not registered" within the form, if it echoes "Email not registered"? My login form contains a div to display the error if necessary.
ajax:
<script>
$(document).ready(function() {
$("#loginform").submit(function(e){
e.preventDefault();
$.post('login/login.php', {email: $('#email').val(), loginsubmit: 'yes'}, function(data)
{
if (data === "redirect")
{
window.location = "http://www.gathercat.com/login/private.php";
}
else {
$("#formResponse").html(data).fadeIn('100');
$('#email').val('');
}
, 'text');
return false;
}
});
});
</script>
PHP:
...
if($login_ok)
{
echo 'redirect';
}
else
{
echo 'That email address is not registered';
}
...
login form:
...
<form id="loginform" name="loginform" method="POST" class="login" action="#">
<input name="email" id="email" type="email" class="feedback-input" placeholder="My Email" required/>
<div id="formResponse" style="display: none;"></div>
<button type="submit" name="loginsubmit" class="loginbutton">Login</button>
...
Full PHP
<?php
$emailaddress = $_POST["email"];
?>
<?php
// First we execute our common code to connection to the database and start the session
require("common.php");
// This if statement checks to determine whether the login form has been submitted
// If it has, then the login code is run, otherwise the form is displayed
if(!empty($_POST))
{
// This query retrieves the user's information from the database using
// their email.
$query = "
SELECT
email
FROM users
WHERE
email = :email
";
// The parameter values
$query_params = array(
':email' => $emailaddress
);
try
{
// Execute the query against the database
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query");
}
// This variable tells us whether the user has successfully logged in or not.
// We initialize it to false, assuming they have not.
// If we determine that they have entered the right details, then we switch it to true.
$login_ok = false;
// Retrieve the user data from the database. If $row is false, then the email
// they entered is not registered.
$row = $stmt->fetch();
if($row) {
$login_ok = true;
}
// If the user logged in successfully, then we send them to the private members-only page
// Otherwise, we display a login failed message and show the login form again
if($login_ok)
{
// This stores the user's data into the session at the index 'user'.
// We will check this index on the private members-only page to determine whether
// or not the user is logged in. We can also use it to retrieve
// the user's details.
$_SESSION['user'] = $row;
// Redirect the user to the private members-only page.
echo 'redirect';
}
else
{
// Tell the user they failed
echo 'That email address is not registered';
}
}
?>
I've rewritten the code for you as it likes like you had quite a few problems.
$(document).ready(function() {
$("#loginform").submit(function(e){
e.preventDefault();
jQuery.ajax({
type: "POST",
url: "login/login.php",
dataType:"text",
data: { email: $('#email').val(), loginsubmit: 'yes' },
success:function(response){
if(response == "redirect"){
window.location.replace("http://www.gathercat.com/login/private.php");
}
else{
$("#formResponse").html(response).fadeIn('100');
$('#email').val('');
}
}
})
});
});
This is untested but please let me know if you have any questions about how it works.
if ( formResponse === "redirect" ) ...
what is formResponse variable?
it should be data
if ( data == "redirect" ) ...
UPDATE:
may be this will help
$(document).ready(function () {
$("#loginform").submit(function (e) {
e.preventDefault();
$.post('login/login.php', {
email: $('#email').val(),
loginsubmit: 'yes'
}, function (data) {
if (data === "redirect") {
window.location = "http://www.gathercat.com/login/private.php";
} else {
$("#formResponse").html(data).fadeIn('100');
$('#email').val('');
}}, 'text');
// this does not matter
return false;
}
// add line below
return false;
});
});
Ok, I solved it!
I changed my ajax to:
<script>
$(document).ready(function() {
$("#loginform").submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "login/login.php",
dataType:"text",
data: {email: $('#emailaddy').val(), loginsubmit: 'yes'},
success:function(result){
if(result === "redirect"){
// window.location.replace("login/private.php");
window.location.replace("http://www.gathercat.com/login/private.php");
//alert(result);
}
else{
$("#formResponse").html(result).fadeIn('100');
$('#emailaddy').val('');
}
}
})
});
});
</script>
and removed some commented-out HTML within the bottom of my php file which was disrupting the "result" variable's content. Everything runs perfectly now. I added this answer so people could see the full code easily, but I'm giving massive credit to paddyfields for their help, thank you again. You too Lee, appreciate the support. Take care

jQuery Form Validation redirect if success validation

I have jQuery Login Form that the function is to check user validation.
Here is the JS :
$(document).ready(function()
{
$('#button_sign_in').click(function(){
console.log('login');
$.ajax({
url: "login",
type: "post",
data: $('#login_form').serialize(),
success: function (data) {
//console.log('data:'+data);
if (data.user) {
$('#lblUsername').text(data.user.username);
}
else {
$('#button_sign_in').shake(4,6,700,'#CC2222');
$('#username').focus();
}
},
error: function (e) {
console.log('error:'+e);
}
});
});
});
The logic is, if wrong username or password then the button will shake. If correct login then redirect to the home page.
and here is my PHP function :
require ("functions/_db_.php");
$username = $_POST['username'];
$password = $_POST['password'];
$query = mysql_query("SELECT username, password FROM t_users WHERE username='$username' && password='$password'");
$found = mysql_num_rows($query);
if ($found > 0)
{
header('location:home.php');
}
Now the problem is : if login corrected, the page won't redirect to home page.
Any suggestions ?
Maybe because you're not doing the redirect itself?
success: function (data) {
//console.log('data:'+data);
if (data.user) {
$('#lblUsername').text(data.user.username);
window.location = '/home.php'; // redirect to the homepage
}
else {
$('#button_sign_in').shake(4,6,700,'#CC2222');
$('#username').focus();
}
}
PHP redirect using header won't work if you send it to the client via AJAX. You have to redirect it on the client-side using JS in this case.
Keep your PHP Script as bellow
//Check your inputs against to mysql injections
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$query = mysql_query("SELECT username, password FROM t_users WHERE username='$username' && password='$password'");
$found = mysql_num_rows($query);
if ($found > 0)
{
$res='SUCCESS';
}
else
{
$res='ERROR';
}
$ary=array("status"=>$res);
echo json_encode($ary); //Json output - we are sending the assynchronus data in json format
and Your Script
$.ajax
({
url: "login",
type: "post",
data: $('#login_form').serialize(),
dataType:'json', //We need ajax data in json type
success: function (data)
{
if (data.status=='SUCCESS') //status is proper of the json object, which we gave in php code in above script
{
window.location='home.php';
}
else
{
$('#button_sign_in').shake(4,6,700,'#CC2222');
$('#username').focus();
}
},
error: function (e) {
console.log('error:'+e);
}
});
if (data.user)
{
$('#lblUsername').text(data.user.username);
window.location = "home.php";
}
Dude, i think you have the problem at PHP side, not the javascript.
Considering this, here is your solution , not location it is Location
header('Location: http://www.example.com/');
Document
When you do AJAX call to a php script, calling header() will not load a new page in the browser. You can respond to AJAX call by echo 'success/fail' and redirect to the desired page yourself by checking the response in the success: part of AJAX. And don forget to set the php session, and check whether the user login made successful or not in the page which you want to display after login. So your code in php will be,
if ($found > 0) {
//set session here
echo 'success';
}
else
echo 'fail';
and in Ajax,
success: function (data) {
if (data == 'success') {
window.location = "home_page.php";
}
else {
$('#button_sign_in').shake(4,6,700,'#CC2222');
$('#username').focus();
}
}
in you hompage php,
check for the session.

returning php session to ajax

I am having trouble getting jQuery ajax to recognise a session. I am creating a php session from a login script, but what is happening is that when ajax loads the authenticated page, the session is always unset. For example, in the secure page, if I refresh the page, the session id changes each time. I have session_start(); in each page. Can someone please show me the correct way to handle sessions with ajax and php? I have spent 2 days and have used google so much, I will probably get an invite to there xmas lunch :-) I have included the relevant code and would be grateful for any help. Thanks
PS. If it makes any difference, I am trying to develop mobile app using jquery mobile.
login html js
$(function() {
$("#kt_login1").click(function() {
var user = $('#user').val();
var pass = $('#pass').val();
if (user == '') {
$("#login_message").html('This field cannot be empty')
$('label[for=user]').addClass("label")
return false;
}
else if (pass == '') {
$("#login_message").html('This field cannot be empty')
$('label[for=pass]').addClass("label")
return false;
}
else $('label[for=user]').removeClass("label");
$('label[for=pass]').removeClass("label");
//alert(user + pass + ok);
data = 'user=' + user + '&pass=' + pass;
$.ajax({
type: "POST",
url: "testajax.php",
cache: false,
data: data,
success: function(data) {
if (data == 'authenticated') {
//alert(user);
document.location = 'secure.php';
}
else $('#login_message').html('You are not authorised');
//$(ok).val('Logged In');
//$("#login").get(0).reset();
//$("#form").dialog('close');
},
error: function(xhr, ajaxOptions, thrownError) {
jAlert('There was an exception thrown somewhere');
alert(xhr.status);
alert(thrownError);
}
});
return false;
});
});
testajax.php
<?php
// test wether the user session is already set
$username = mysql_real_escape_string($_POST['user']);
$pass = mysql_real_escape_string(md5($_POST['pass']));
mysql_connect('localhost', 'root', '');
mysql_select_db('sample');
//now validating the username and password
$sql="SELECT * FROM user_usr WHERE username_usr='$username' and password_usr='$pass'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
//if username exists
if(mysql_num_rows($result)>0) {
session_start();
$_SESSION['u_name']=$row['name_usr'];
/*
echo '<pre>';
print_r( $_SESSION['u_name'] );
print_r( $_REQUEST );
echo '</pre>';
exit;
*/
echo 'authenticated';
}
else
{
echo 'Unknown User';
}
?>
+++++SOLUTION+++++
Changed form input from submit to button and voila. All ok
you have to call session_start() each time working with a session (not only when creating it)
see: http://php.net/manual/en/function.session-start.php
There are a whole load of reasons this might be the case - but you're code is upside down! This may well be the cause (or a contributory factor).
You should not treat the existence of a session as evidence of authentication (the contents of the session is another thing altogether). Call session_start() at the top of your script - not conditionally, half-way through.
As to why your session data is not available...that's an FAQ here - have a look at some of the previous answers for potential causes / how to investigate.

AJAX to check the login name exists or not

i have a login box...
when the user starts typing.. i want to check whether the LOGIN NAME entered exists in the database or not...
if the login name is exist i am going to set the login button active... if it doesnot exist i am going to set the login button deactive...
offcourse i am going to need AJAX to perform my mySQL via PHP tough i don't know how it will be done...
lets say this is my query
<?php
$result = mysql_query("SELECT * FROM accounts WHERE name='mytextboxvalue'");
?>
how to do it
keep it simple:
$(document).ready(function(){
var Form = $('#myForm');
var Input = $('input.username',Form)
Input.change(function(event){
Value = Input.val();
if(Value.length > 5)
{
$.getJSON('/path/to/username_check.php',{username:Value},function(response){
if(response.valid == true)
{
Form.find('input[type*=submit]').attr('disabled','false');
}else
{
Form.find('input[type*=submit]').attr('disabled','true');
}
});
}
});
});
and then PHP side..
<?php
//Load DB Connections etc.
if(!empty($_REQUEST['username']))
{
$username = mysql_real_escape_string($_REQUEST['username']);
if(isset($_SESSION['username_tmp'][$username]))
{
echo json_encode(array('valid' => (bool)$_SESSION['username_tmp'][$username]));
die();
}
//Check the database here... $num_rows being a validation var from mysql_result
$_SESSION['username_tmp'][$username] = ($num_rows == 0) ? true : false;
echo json_encode(array('valid' => (bool)$_SESSION['username_tmp'][$username]));
die();
}
?>
You can use JSON-RPC, here is implementation in php.
and in JQuery you can use this code.
var id = 1;
function check_login(){
var request = JSON.stringify({'jsonrpc': '2.0',
'method': 'login_check',
'params': [$('#login_box').val()],
'id': id++});
$.ajax({url: "json_rpc.php",
data: request,
success: function(data) {
if (data) {
$('#login_button').removeAttr('disabled');
} else {
$('#login_button').attr('disabled', true);
}
},
contentType: 'application/json',
dataType: 'json',
type:"POST"});
}
and in php
<?php
include 'jsonRPCServer.php';
//mysql_connect
//mysql_select_db
class Service {
public function login_check($login) {
$login = mysql_real_escape_string($login);
$id = mysql_query("SELECT * FROM accounts WHERE name='$login'");
return mysql_num_rows($id) != 0;
}
}
$service = new Service();
jsonRPCServer::handle($service);
?>
Look at jQuery AJAX and jQuery TypeWatch
But like #halfdan said, this is a potential security risk. I have never seen a site do this with a username, only with search results.
Your potentially giving away an end point (URL) on your web site which anyone could query to find out if a username is valid. Intranet or not, it is a risk.

Categories