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.
Related
I have a problem with a session variable, I have used it well up until now but after implementing the logout logic, after relog I am unable to store my session variable again.
For the log in I use an ajax request that looks like this:
if ($row['password'] == $entered_password) {
if (!isset($_SESSION['user_email'])) {
$_SESSION['user_email'] = $entered_email;
} else {
unset($_SESSION['user_email']);
$_SESSION['user_email'] = $entered_email;
}
echo "login_validated";
exit;
} else {
echo "invalid_password";
exit;
}
and the request is:
$.post('php/login.php', {
emailLogin: emailLogin,
passwordLogin: passLogin
}, function (responseText) {
if (responseText === "invalid_username") {
alert ("Username is invalid! Please check it again or make sure you have already registered first!");
} else if (responseText === "invalid_password") {
alert ("Given password is incorrect! Please try again.");
} else if (responseText === "login_validated") {
window.location.href = "php/pages/expenses.php";
} else {
console.log(responseText);
alert ("A problem occured at te server level, please try again later! If problem persists, please contact us!");
}
});
But after implementing and using the following logic for the log out, my session variable value it's not saved and displayed anymore:
$(document).ready( function (event){
$('#logoutButton').click(function (event) {
event.preventDefault();
var user_response = confirm("Are you sure you want to logout? Your current session will be closed!");
if (user_response === true) {
<?php
if (isset($_SESSION['user_email'])) {
unset($_SESSION['user_email']);
}
session_destroy();
?>
window.location.href = "../../index.php";
}
});
});
I mention that I've first tried to use a separate file for the logout with header redirect, but was blocked by my built in adblocker similar ad-blocker error. I have supposed that maybe on my previous login actions I have made too many session variables, and proceeded to clean all my cookies. It did not had any effect. Also, read other posts and the documentation and still have no clues what I have done wrong.
Also, regarding being sure to clean all previously stored session vars, I have called once the function: http://php.net/manual/ro/function.session-unset.php session_unset. Again, no improvement seen so far. I've kept trying to read the documentation but nothing seems wrong with my code, and in aother similar forum posts I have not found anything useful. Thank you in advance!
EDIT: Short mention about the password - yes, currently they are stored in plaintext, but it is just a personal project, and upon finishing I will also implement a salt and pepper encryption on passwords.
Many thanks to you #Syscall! Almost crazed about this :) Kept everything the same, just modified the php script inside the front end to an ajax request:
`var user_response = confirm("Are you sure you want to logout? Your current session will be closed!");
if (user_response === true) {
$.ajax({url: "../logout.php", success: function(result){
console.log(result);
window.location.href = "../../index.php";
}});
}`
also added a session_start(); in the logout file. Now all the logic works, logging in, logging out, trying on different users and so on.
I am able to the js file to fire which does do the first alert but i cannot get the 2nd alert to happen, php file is there and working returning 0 but the alert('finished post'); is not coming up. I think its some syntax I am missing.
$(function () {
$("#login_form").submit(function () {
alert('started js');
//get the username and password
var username = $('#username').val();
var password = $('#password').val();
//use ajax to run the check
$.post("../php/checklogin.php", { username: username, password: password },
function (result) {
alert('finished post');
//if the result is not 1
if (result == 0) {
//Alert username and password are wrong
$('#login').html('Credentials wrong');
alert('got 0');
}
});
});
});
Here is the php
session_start();
include 'anonconnect.php';
// username and password sent from form
$myusername= $_POST['username'];
$mypassword= $_POST['password'];
$sql = $dbh->prepare("SELECT * FROM Users WHERE UserLogin= :login");
$sql->execute(array(':login' => $myusername));
$sql = $sql->fetch();
$admin = $sql['admin'];
$password_hash = $sql['UserPass'];
$salt = $sql['salt'];
/*** close the database connection ***/
$dbh = null;
if(crypt($mypassword, $salt) == $password_hash){
// Register $myusername, $mypassword and redirect to file
$_SESSION['myusername'] = $myusername;
$_SESSION['loggedin'];
$_SESSION['loggedin'] = 1;
if($admin == 1){
$_SESSION['admin'] = 1;
}
header("location:search.php");
}
else {
$_SESSION['loggedin'];
$_SESSION['loggedin'] = 0;
echo 0;
}
Ok so I'll take a stab at this, see if we can work this out. First, let's clean up your code a little bit - clean code is always easiest to debug:
$(function () {
$("#login_form").on('submit', function(){
console.log('form submitted');
// get the username and password
var login_info = { username: $('#username').val(), password: $('#password').val() }
// use ajax to run the check
$.ajax({
url: '../php/checklogin.php',
type: 'POST',
data: login_info,
success: loginHandler
error: function(xhr, status, err){ console.log(xhr, status, err); }
});
return false;
});
function loginHandler(loggedIn){
if (!loggedIn) {
console.log('login incorrect');
} else {
console.log('logged in');
}
}
});
...ok great, we're looking a little better now. Let's go over the changes made quickly.
First, swapped alerts for console.logs - much less annoying. Open up your console to check this out -- command + optn + J if you're using Chrome.
Second, we compressed the login info a bit - this is just aesthetics and makes our code a little cleaner. Really you should be using variables when they need to be used again, and in this case you only use them once.
Next, we swapped the $.post function for $.ajax. This gives us two things -- one is a little finer control over the request details, and the second is an error callback, which in this case is especially important since you almost certainly are getting a server error which is your original problem. Here are the docs for $.ajax for any further clarification.
We're also pointing the success handler to a function to minimize the nesting here. You can see the function declared down below, and it will receive the data returned by the server.
Finally we're returning false so that the page doesn't refresh.
Now, let's get to the issue. When you use this code, you should see a couple things in your console. The first will probably be a red message with something like 500 internal server error, and the second should be the results of the error callback for the ajax function. You can get even more details on this in Chrome specifically if you click over to the Network Tab and look through the details of the request and response.
I can't fix your PHP because you didn't post it, but I'll assume you'll either follow up with an edit or figure that out yourself. Once you have the server issue ironed out, you should get back a clean console.log with the response you sent back, and you can move ahead.
Alternately, this will work because of the lack of page refresh in which case you can ignore the previous 2 paragraphs and declare victory : )
Hope this helps!
Ah, so damned obvious. You aren't cancelling the default submit action so the form is submitting normally. Add this
$("#login_form").submit(function (e) {
e.preventDefault();
// and so on
See http://api.jquery.com/event.preventDefault/
you need to change 2nd line and add the e.preventDefault to prevent the form from refreshing the whole page.
$("#login_form").submit(function (e) {
e.preventDefault();
Also I would change the AJAX request to use GET and change the code in PHP to read variables from GET so you can easily test the PHP page is working by running it in the browser like this
checklogin.php?username=x&password=y
try this:
$("#login_form").submit(function () {
alert('started js');
//get the username and password
var username = $('#username').val();
var password = $('#password').val();
//use ajax to run the check
$.post("../php/checklogin.php", { username: username, password: password }, function (result) {
alert('finished post');
//if the result is not 1
if (result == '0') {
//Alert username and password are wrong
$('#login').html('Credentials wrong');
alert('got 0');
}
}, 'text');
});
}, 'text');
maybe the server does not give the right data format. for example, if you request for json, and the jQuery cannot convert result sting to json. then the function would not be executed and then you would not able to get 'alert('got 0');' thing.
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.
I have a login form using jquery ajax and a php code. The issue is that is always returns an error instead of logging me into the system. I have spent days trying to find the error but I can't. The webpage displays no errors if I visit it directly. This used to work about a week ago until I accidentally deleted the jquery and now I can't get it to work.
Here is the PHP code:
include('.conf.php');
$user = $_POST['user'];
$pass = $_POST['pass'];
$result = mysql_query("SELECT * FROM accountController WHERE username = '$user'");
while ($row = mysql_fetch_array($result)) {
if (sha1($user.$pass) == $row['pword']) {
setcookie('temp', $row['username']);
session_start();
$_SESSION['login'] = 1;
$_SESSION['uname'] = $row['username'];
echo "success";
}
}
and here is the Jquery AJAX code:
var username = $('#main_username').val();
var password = $('#main_pword').val();
$('.mainlogin').submit(function() {
$.ajax({
url: 'log.php',
type: 'POST',
data: {
user: username,
pass: password
},
success: function(response) {
if(response == 'success') {
window.location.reload();
} else {
$('.logerror').fadeIn(250);
}
}
});
return false;
});
How would I check to see what is being returned like blank or success from the server. Is there any extension for safari? Thanks!
Put this in, instead. It will alert the server's response in a popup.
success: function(response) {
alert(response);
}
On your PHP side, try outputting more stuff - add an }else{ to your if statement that returns some useful data, for example
}else{
print("Post is: \n");
print_r($_POST);
print("\nMySQL gave me: \n");
print_r($row);
}
Just make sure you don't leave it in once it's working!
Look for:
hash is different
db field is different
db fields are blank for some reason
POST data is wrong / wrong field names
Edit: Here's another issue: Your first four lines should actually be:
$('.mainlogin').submit(function() {
var username = $('#main_username').val();
var password = $('#main_pword').val();
$.ajax({
Your code as it is gets the values before the form is submitted - at load - when they are blank, and as a result is sending blank strings to the server as username and password.
Take a look at the code i have in this answer here: user check availability with jQuery
You need to json encode your response, also Firefox has Firebug you can use to view your ajax post and response, chrome and IE both have developer tools
Safari also has dev tools: http://developer.apple.com/technologies/safari/developer-tools.html
Check the console to see what is happening with your AJAX
so i'm writing something similar to a chat app and need a way to detect when a user is no longer active. essentially i need to let OTHER users of the app know that user X logged out if they left the page or closed their browser. Any way for a server-side script to figure this out aside from "i got no requests from user X in 15 mins so i'll assume he's out?"
Just as they said in the links in the comments you need to use AJAX. The easiest way to do this (in my opinion) is with JQuery, here is an example below:
$(document).ready(function(){
window.setInterval(function(){
initiateSessionCheck();
5000);
function initiateSessionCheck() {
$.ajax({
type : 'POST',
url : 'sessioncheck.php',
success : function(data){
//success
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
//error do something they are no longer active
}
});
}
});
Now in your sessioncheck.php file you'll want to do this
session_start();
if (!$_SESSION) { //you could check a session variable explicitly like $_SESSION['user_id'] != ''
$return['error'] = true;
} else {
$return['error'] = false;
}
echo json_encode($return);
It's basic but it should do the trick!