Setting a Cookie
Permalink 1 user found helpful
Hi, I have a form in view.php
After the form submits I need to reload the page a second time before I see the cookie values, I want to see them when the page reloads the first time after the form is submitted.
I must need to do something other than just the return?
Thanks for any help!
Peter
<form method="post" action="<?php echo $this->action('favorite_cookie')?>"> <INPUT type="hidden" name="favoriteID" value="<?=$mls?>"> <INPUT type="submit" value="Add To Favorites"> </form> And a function in controller.php function action_favorite_cookie() { setcookie("ccmFavorite", $_REQUEST['favoriteID']); return; } and for testing in a separate block on the same page as the form I have: print_r($_COOKIE);
After the form submits I need to reload the page a second time before I see the cookie values, I want to see them when the page reloads the first time after the form is submitted.
I must need to do something other than just the return?
Thanks for any help!
Peter
So by the time setcookie() is called in your code, the server has already received the request from the browser (and hence all of its cookies) -- your code is now just sending this cookie to the browser for the first time.
The server isn't going to see that cookie that it just sent until another page is requested by the browser (hence the appearance in $_COOKIE after a reload).
There are 2 ways to solve this issue:
1) Force a page reload after the cookies are set.
2) Instead of checking $_COOKIE in your view, put some code in your controller's on_page_view() function that passes the desired $_COOKIE value to the view IF it exists. Then, in your action_favorite_cookie() function, ALSO pass this variable to the view after calling setcookie(). This way, your view is receiving the variable one way or another, whether it came from $_COOKIE, or from your action_favorite_cookie() function.
HTH!