set PHP cookie on click

11,981

Solution 1

setcookie does not affect the current request. To do that, you also need to manually set the relevant $_COOKIE variable:

setcookie("HideUpdates",$_COOKIE['HideUpdates'] = "hide", time()+60*60*24*5, "/", $vars->networkSite);

Solution 2

The only way to do it is JS or jQuery because, as the other people say, cookies does not affect the current page request.

You need jquery cookie plugin for the jQuery solution. Some servers have problems with jquery.cookie.js (The solution is to rename the file E.g.: jquery.cook.js)

Usage of jquery cookie plugin

Create session cookie:

 $.cookie('the_cookie', 'the_value');

Create expiring cookie, 7 days from then:

 $.cookie('the_cookie', 'the_value', { expires: 7 });

Create expiring cookie, valid across entire site:

 $.cookie('the_cookie', 'the_value', { expires: 7, path: '/' });

Read cookie:

 $.cookie('the_cookie'); // => "the_value"
 $.cookie('not_existing'); // => undefined

Read all available cookies:

 $.cookie(); // => { "the_cookie": "the_value", "...remaining": "cookies" }

Delete cookie:

 // Returns true when cookie was found, false when no cookie was found...
 $.removeCookie('the_cookie');

// Same path as when the cookie was written...

 $.removeCookie('the_cookie', { path: '/' });

You can try localStorage. It works on Chrome, FF and IE9 and up. We do not support IE7-10! Hooray!

IE8 have some issues with localStorage.

Script must be inside the $(document).ready(function() {});

$(document).ready(function() {
   $("#btnClick").click(function(e) {
      e.preventDefault();
      localStorage.setItem('cookieName', 'cookie_value');
  window.href.location = "your_new_page.php";   
   });


   //On the same page or other page

   if (localStorage.getItem('cookieName')){
      //do here what you want


   }else{
      //do something else

   }

});

Solution 3

Cookies don't kick in until after they are set and a new page request is sent. This is because cookies are sent with page requests, they just don't magically appear to a the server.

Your solution is to do a page refresh after setting the cookie.

Share:
11,981

Related videos on Youtube

Xhynk
Author by

Xhynk

I've been working at a small firm in Oregon as the Lead Developer since 2011. I'm proficient in PHP, CSS3/SCSS, HTML5, Javascript, with a deep knowledge of WordPress Plugin and Theme development. Problems that require innovative solutions are my favorite to work on. Shockingly, I also enjoy rewriting my old code to make it more efficient and chuckle at what I "used to know". Always strive to learn more! You can contact me here: https://xhynk.com/ If you'd like, buy me a coffee - Heaven knows I drink enough of it... https://ko-fi.com/xhynk Looking to market your business? I'm also the lead engineer of WhirLocal, and you can get started getting more reviews, recommendations, and referrals for free: http://whirlocal.io/get-started

Updated on September 16, 2022

Comments

  • Xhynk
    Xhynk over 1 year

    So I'd rather not use JS/jQuery for this - but I can't seem to get this to work.

    I've got a link <a href="?hideupdates=hide">Hide Updates</a> which I'm trying to set a cookie with.

    if($_GET['hideupdates'] == 'hide'){
        setcookie("HideUpdates", "hide", time()+60*60*24*5, "/", $vars->networkSite);
    }
    

    it "works", but I have to click the link twice.


    from "site.com" I can var_dump() the cookie and it comes up NULL

    Now I click the link and go to "site.com?hideupdates=hide" and the cookie still comes up NULL

    However, from "site.com?hideupdates=hide" when I click the link again - THEN the cookie comes back hide.

    Am I missing something? Or do I 'have' to use JS/jQuery for this?

    • Marc B
      Marc B over 11 years
      remember: superglobals are populated BEFORE php hands over control to your script. Their values will NOT be changed by anything done in your script, unless you explicitly push the changes to the superglobals. Those changes will otherwise only be reflected in the superglobals the NEXT time your script runs.
  • Xhynk
    Xhynk over 11 years
    I didn't realize, but you're right. Refreshing was the same as clicking the link again. I was under the impression it would be populated before everything.