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.

 

 

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.