...

View Full Version : PHP and Ajax problems (cookie and session)



Lazaroth
07-06-2008, 01:29 AM
Hi.

I have 2 problems I would like to get answered.
Neither needs any "real" code displayed from my side, since it's not therein the problems lies.
Note that this is also simplified, to better demonstrate what I mean.

1.
I have a page where when a link is pressed ajax is called and it eventually runs a php function.
This function does 2 things. First sets a cookie, then echo's stuff into a predefined layer.



function setUsername($name)
{
setcookie("uname", $name, 0, "/");
echo "Username: " . $_COOKIE["uname"];
}


The problem is that the cookie doesn't exist until ajax is done.
The above code would give an error saying that cookie doesn't not exist.
I've tried sleep etc, but it seems to depend on if ajax has finished.
Why is that so and how can I circumvent this?

2.
Are there any good ways to combine sessions and ajax?
I've tried http://codinginparadise.org/weblog/2005/08/ajax-tutorial-saving-session-across.html but it has flaws.
I can get neither example to work in safari and when the techniques are used in FF/IE,
they only work in a .htm/.html file. If I try them in .php the field/iframe is reset on refresh.

Thanks in advance!

shyam
07-06-2008, 02:23 PM
as you've already realized the cookie value becomes available only after the completion of the ajax request. this is because cookies are set on the browser using http headers so, they must reach the browser to be set and sleeping on the server-side isn't going to help.

now, one way to do it would be to simply set the cookie in the ajax call and when the call completes read the uname value from the cookie using javascript

Lazaroth
07-06-2008, 03:03 PM
Ah, so that is how it works.

Your suggestion is simple yet brilliant, I'll try something like that later tonight! :)

Lazaroth
07-06-2008, 06:44 PM
Works like a charm!

Now if I only could get sessions to work aswell... :)

barkermn01
07-07-2008, 09:14 AM
Same way mate
Ajax -> php $_SESSION['name'] = $value
AJAX Complete

AJAX -> php echo $_SESSION['name'] - and get javascript to save it as var and there you go
AJAX Complete

Lazaroth
07-07-2008, 02:51 PM
I think I know how you mean, although I'm not sure how to do it.

First, through ajax set session = some value


Ajax -> php $_SESSION['name'] = $value
AJAX Complete


Secondly, though ajax get the session and send to javascript so everything can be read.


AJAX -> php echo $_SESSION['name'] - and get javascript to save it as var and there you go
AJAX Complete


The thing I don't understand is since session is set though ajax, the session isn't really set. And that is the problem with using ajax and sessions.
So if I try to get it in an other call, it will show session undefined.
Have I misunderstood how ajax works or am I missing something else?



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum