Jump to content

Sessions don't seem to be available on other pages when using ajax?


rv20

Recommended Posts

I am using using ajax to POST (not GET) a form so it goes something like,

 

(1)Form SUBMIT(login.php) -->(2)ajax XMLHttpRequest -->(3) PHP validating script(validate_login.php) --> (4)ajax responsetext --> (5)output reponsetext on page, or whatever you need to do with responsetext.

 

So if the login is valid, I CAN'T do a

 

header("location: users.php");

 

from the validating login script as I just get errors as I am using ajax and not standard form posting.

 

So what I do is if the login passes the validation is, I set a session and also send an echo from, validate_login.php,

 

session_start();
$_SESSION['user'] = $_POST['username'];
echo "users.php";

 

and I can see in Firefox cookies that the session is created.

 

then at (4/5) AJAX (responsetext) I do

 

if(mypostrequest.responseText == "users.php"){
window.location.href = "users.php";
}

 

This all works perfect but here is the problem, once i am in users.php if i do a,

 

echo $_SESSION['user'];

 

 

then nothing, no output, I must be doing something wrong or maybe because I am using ajax that is making it not work??

 

Thanks for any help.

this may be a silly question but are you sure that you have

session_start();

 

on the users.php page?

 

So I need session_start(); on the users.php as well as the validate_login.php ??

 

Beacuse no i don't have it on users.php, i thought you just called session_start(); once ever on whatever page you create the session on.

Well that would explain it, i will try.

 

yep you will need to call

 

session_start();

 

on all pages that you intend to use session variables on.

 

I you include a particular file on every page that uses session variables ie.

 

include("somefile.php");

 

then you can just add it to that file (just saves typing it on every page).

The best approach is to learn how to use mod_rewrite to send all web requests that are not images through a single file index.php.

 

This will make your URLs pretty.

 

It also makes handling global application logic much easier since you only need to put session_start() in one place (at the top of index.php).

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.