0

I have a cookie and need to read it with JQuery or just javascript if JQuery alone is not possible.

Then I need to pass the value of that Cookie to a PHP variable

Can this be done?

UPDATE: I need everything to happen in the same page.

  1. Javascript reads the already existing cookie.
  2. $somePHPvariable = MyJavascriptCookieValue;

I need to use Javascript to read this cookie because I am using a wordpress cookie created in function.php and php cannot read the cookie when it's create but after the next reload of the page, which is no good to me.

2
  • Why do you need to read it in jQuery/JavaScript first? Are you going to manipulate the value? Why dont you just read the cookie in PHP and assign it to a variable? Commented Feb 2, 2012 at 19:17
  • This is implicit in Jasper's answer below, but one thing worth pointing out is that when a page loads the PHP will be executed before any client side Javascript. So you can't pass the result of any js code to PHP code in the same page load. You can reload the page with the js result in the querystring, or use ajax to pass the result to the server. Commented Feb 2, 2012 at 19:22

3 Answers 3

1

In PHP you can directly get the value of the cookie with $_COOKIE['variable_name']...

If you really want to get the value of the cookie in JavaScript then here is one of a few different plugins to help read/write cookies with jQuery: https://github.com/carhartl/jquery-cookie

You can then use AJAX to send the cookie information to your PHP script:

$.ajax({ url : 'path/to/server-side.php', data : { cookie : $.cookie('the_cookie_name') } }); 

This will send the cookie as the GET variable cookie. You will be able to access it via PHP like this: $_GET['cookie'].

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

1 Comment

Check-out my answer now, I think I updated it just after you posted your comment.
1

You can access cookies in JavaScript via document.cookies, look here for details.

But if you want to access the cookie data in php, you could read the cookie in php from the variable $_COOKIE["coockiename"].

Comments

1

Browser sends cookies to you server with the request each time. You dont need any javascript or jquery or ajax requests to get it. Just use $_COOKIE global array in PHP.

1 Comment

Please see UPDATE and you'll know which I cannot use php to read this cookie value

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.