views:

260

answers:

3

How can I setcookies in php server side with ajax and read cookies in the real time with javascript?

Example: After pressed "ok" button, the client side will call ajax and ajax will call to php server side to collect data. It will also assign value into cookies in php server side while it's getting the data. At the sametime, I want to read the assigned value cookies with another function in real time(function will call from the ajax when it's start calling to php server) and display the cookies value on the client side.

I tried this many time, but seem like the function can only get the updated cookies value after the ajax process is complated.

+1  A: 

How would you be able to read a cookie on the client before it has arrived there?

  1. you make an (ajax, or otherwise) request to the server
  2. the server assembles a response, adding a cookie to it
  3. the client receives the response
  4. after the response is there, it can examine the cookie value

To me your question sounds like you try to read the cookie right in step 1. This won't be possible.

If that's not what you are trying to do, then your question needs some re-wording. :)

Tomalak
A: 

Cookies exist only on the client side. They're included with each HTTP request, allowing the server to perform actions on them. Javascript can set these cookies for you if you need:

// http://www.quirksmode.org/js/cookies.html#script
function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}
nickf
A: 

Take a look at this page discusses Comet which seems like what you want.

BeWarned