tags:

views:

110

answers:

3

I create the cookie in jQuery. I can verify it in Firefox. But when I try to print the cookie or assign into another value I cant get it. I also use sessions. And I started the session in PHP. My code to print or assign the cookie value is shown below

echo $_COOKIE['a'];

for assigning the value

$b=$_COOKIE['a'];

The cookie created using jQuery is

$.cookie("a",$(this).val());

Where did I make a mistake? How can I get the cookie value?

A: 

Looks fine to me. To debug the issue, try:

var_dump($_COOKIE);

and also:

List Cookies in Javascript

Richard Nguyen
+1  A: 

It is possible to set the cookie in PHP entirely without jQuery at all..

..however...

It appears you are using jQuery in this way.

What may be causing a problem is a few things:

a) $(this).val() possibly might be returning NULL.

b) You are not setting the path and expiration on the cookie. If you have subdirectories it is normally good to set a master cookie that is the root path '/'.

To read your cookie using PHP, try this...

  $cookies = explode(';', $_SERVER['HTTP_COOKIE']);

...and search the array for your "a" cookie.

Further docs on setting and reading cookies using entirely PHP, check here.

You must call this function before any other code is echoed to the page. (before headers)

Talvi Watia
I used the $cookies = explode(';', $_SERVER['HTTP_COOKIE']); When I print the array it returns only the one cookie value which is not my expecting one.It is used in the login session.But if i use firefox and see Tools->PageInfo->Security->Viewcookie There is a cookie "a" with the correct value.But I cant access in PHP?Why?I am eagerly waiting for ur answer...
vinothkumar
make sure you do not have exception blocking for your domain set on allowing cookies or 3rd party cookies. also when you set your cookie, make sure you set the root path "/". your browser will not send a cookie from a subdirectory unless you are accessing that same subdirectory.
Talvi Watia
Thanks Talvi Watia your answer is helpful to me....Thanks a lot I did the mistake in the path....You are genius to answering
vinothkumar
+3  A: 

To set the value of a cookie in PHP, use the setcookie function:

setcookie("a", "foobar");

Doing this, however, requires that you run the code before you output to the client (and send the HTTP headers. So basically, you can't do something like this:

<div>
<p>Here's my cookie!</p>
<?php
setcookie("foo", "bar");
?>
</div>

You would need to call setcookie before you have any of your HTML.

Also, if you set the cookie value on the client, you need to be making a request from that client to get the cookie value. If you're just running arbitrary code on the server, the client isn't sending it's cookie back up.

Lastly, the page that the server is processing and the page that the JS is on need to be in the same domain. If they're not, the browser doesn't send up the appropriate cookie.

Hope this helps!

mattbasta