0

I'm using this javascript function to setup a cookie on my site that will show a div wile the cookie isn't setup.

function accept_cookies(){
    days=365; // number of days to keep the cookie
    myDate = new Date();
    myDate.setTime(myDate.getTime()+(days*24*60*60*1000));
    document.cookie = 'cookie_t=1; expires=' + myDate.toGMTString();
}

usage:

<a onClick="HideContent('cookies'); accept_cookies()" href="javascript:HideContent('cookies')">
    ok
</a>

This method works great on my desktop device but, on my android phone it doesn't work so well. I know this because I click the link several times and the div keeps on showing after it the link saying that is ok.

Polyov
  • 2,281
  • 2
  • 26
  • 36
bpy
  • 1,150
  • 10
  • 27

1 Answers1

1

You can use the php method "setcookie" to create a Set-Cookie header, that will set a cookie on the client side.

http://php.net/manual/en/function.setcookie.php

Processes that happens in the server side (php) are much more reliable than on the client side.

Usage example with php and ajax jquery library:

<a href="#" onClick="ajaxPost()">active</a>

function ajaxPost(){
   $.post("action.php",{action: "setTheCookie"}, function(result){
    // Do something
   }
}

action.php

checkAction();
function checkAction(){
   if($_POST["action"] == "setTheCookie")
     setCookie("cookie name", "cookie value", time() + (86400 * 30), "/");
   exit();
}
MrWhite
  • 43,179
  • 8
  • 60
  • 84
Furybone
  • 31
  • 5
  • How can I do that? can you point an example or a good tutorial? Please don't forget that I need to be set onClick – bpy Jul 30 '16 at 17:15
  • you can try this tutorial to setcookie with php: http://www.w3schools.com/php/func_http_setcookie.asp and you need that onClick will make an ajax or get/post action, that will active the php page with the setcookie function. example: http://stackoverflow.com/questions/19323010/execute-php-function-with-onclick – Furybone Jul 30 '16 at 20:32