Jump to content

Javascript version of this php line


toolman

Recommended Posts

To test if a cookie is set or not you'd use this:

 

if (document.cookie.indexOf('eucookie=') == -1){
  //cookie is not set
}
else {
  //cookie is set
}

 

You can't conditionally include/exclude blocks of HTML with JS like you can with PHP though (by just wraping it in an if).  You'd have to convert the HTML into a JS string and use document.write or do something onload.

 

 

Thanks. I now have this

 

<script>

   if (document.cookie.indexOf('eucookie=') == -1){
 //cookie is not set
 document.write('hello');
}
else {
 //cookie is set
 document.write('bye');
}
   </script>
<a href="javascript:"  onclick="SetCookie('eucookie','eucookie','time()+31556926')">

 

I am trying to create the cookie when the link is clicked, but it isn't working :(

 

Any ideas why?

 

Thanks

Did you create/import a setcookie() function with javascript, or are you trying to call PHP's setcookie function?  If the latter then, you can't do it like that, you need to use ajax or reload the page (ie, use a normal link to a .php file, not onclick).

 

Either way, the value you're passing as the third parameter is almost surely wrong.  If you're trying to use PHP's setcookie, you need to remove the quotes around the third parameter.  If you have a JS function then it probably would be expecting a Date object, read the docs for the function.

 

Lastly setting the cookie isn't going to cause the if to be re-evaluated and appear right away, you'd need to reload the page to see it change.

 

An Example

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.