1

Using Javascript & Jquery, I'm creating a cookie on a click event, and then redirecting the user to another page. I'm doing that like this:

<script type="text/javascript">
$(".my-div").click(function() {

document.cookie ="answers=:" + myAnswers + "; path=/; domain=.mydomain.com;";

setTimeout("location.href = '/my-destination-page.php/';", 5000);

});

</script>

When I reach my-destination-page.php, I can see the cookie is set correctly in Google Developer Tools. However, PHP doesn't detect that it's set:

<?php
var_dump($_COOKIE['answers']);
?>

The above returns a big fat NULL.

Any ideas why this is happening?

3
  • Have you tried var_dump($_COOKIE); to see if it's in there? Commented Aug 11, 2015 at 17:39
  • I did. It returns array(0) { } Commented Aug 11, 2015 at 17:42
  • Check the request itself, make sure the cookies header is set when destination.php is requested. I wonder isn't the cache problem here (so that request isn't even sent by the browser). Commented Aug 11, 2015 at 17:45

2 Answers 2

1

try to change,

document.cookie ="answers=:" + myAnswers + "; path=/; domain=.mydomain.com;";

to

document.cookie ="answers=:" + myAnswers + "; expires=Thu, 12 Aug 2015 20:47:11 UTC;path=/; domain=.mydomain.com;";

and check

Sign up to request clarification or add additional context in comments.

2 Comments

I tried, but it didn't change the result. At this point, I think I'm going to go with sessionStorage instead of writing a cookie (since I don't need this cookie to last more than a session).
Actually, you were right. I must have made a mistake when I copied / pasted your expires code before. Since I just want this particular cookie to last a session, I set expires to 0, and I'm able to read it perfectly. THANK YOU!
0

I didn't test your specific code -- but I know building raw cookie strings manually is a finicky, error prone thing. If you get something wrong the cookie processing code on the server (won't recognize your cookies).

Since you're already using jQuery, I'd try using the jQuery cookie plugin. Even if you don't want to deploy with this plugin, you can use it to set your cookie, examine the request headers, and determine where your cookie string is incorrect (or determine that your cookie strings is correct, and that your problem lies elsewhere)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.