3

I am creating a cookie in CakePHP using setcookie() from /cake/contoller_name/method/parameter this page. But I could not read this cookie from JavaScript. However, when the above cookie sets from /cake/contoller_name/method this page, I can read this cookie from JavaScript.

So I realized we cannot set and change the cookie from the page with parameters. In the server side that in Cake we can read get these cookies, but not from JavaScript. Note: the params are passed in "cake style", not on a regular querystring; e.g.: /cake/controller/param1/param2. Example Code

Case 1: URL: /cake/payroll/salary Page: payroll_controller.php

function salary(){ 
    setcookie('TEST_COOKIE','TEST_DATA',0); 
}

Case 2: URL: /cake/payroll/salary/14 Page: payroll_controller.php

function salary(){ 
    setcookie('TEST_COOKIE','TEST_DATA',0); 
} 

Javascript Code:

function getCookie(c_name) {
    var i, x, y, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x == c_name) {
            return unescape(y);
        }
    }
}

alert(getCookie('TEST_COOKIE'));

I can read the cookie from Case 1 with JS, but not the cookie from Case 2. How can I set cookies on any page from CakePHP and read those cookies from JavaScript?

2

2 Answers 2

3

There are 3 steps that you must follow:

  1. Use the CakePHP Cookie Component. Let the framework do the hard tasks: http://book.cakephp.org/2.0/en/core-libraries/components/cookie.html

  2. Read this article regarding JavaScript and cookies. You will also find here 3 functions that you should use for deleting/creating/reading cookies: http://www.quirksmode.org/js/cookies.html

  3. If you use Firefox, install Firebug and use the FireCookie extension: http://www.softwareishard.com/blog/firecookie/

Latest Firebug already has FireCookie installed.

In FireCookie you can check if the cookies really exist and view their name and value.

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

Comments

1

try this code to set cookie

setcookie('TEST_COOKIE','your data',0,"/"); 

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.