We help IT Professionals succeed at work.

Convert PHP session cookie to JS

Hey there,  I have a PHP session cookie on our site which sets when a visitor comes to our site from a paid ad, and follows them through the site, and passes the variable to our CRM when they fill out a form.

See the PHP code below. Works!

function set_ad_cookies() {
	
	$vars = array('wordpress_sourcetagji');
	foreach ($vars as $k) {
		if (isset($_GET[$k]) && !isset($_COOKIE[$k])) {
			setcookie($k, $_GET[$k], 0, '/', $domains['cookie_domain']);
		}
	}
	
	  if (!isset($_COOKIE['wordpress_sourcetagji'])) {
		setcookie('wordpress_sourcetagji', $_GET['wordpress_sourcetagji'], 0, '/', $domains['cookie_domain']);
	  }
  }
  add_action('init', 'set_ad_cookies');

Open in new window


We are now finding that caching is stripping the cookie value when they navigate to a different page. Flywheel have said that this will happen as it's php and need to keep the caching on, and the only solution is to create the cookie in JS.

I've got very basic js skills, so how could i convert the above PHP code into JS so that   Scenario :
User1 comes into the site from an ad  https://mysite.com/?wordpress_sourcetagji=this-monster-cookie
User 1 visits varous pages on our site, and then fills out a form.
Cookie is still active and keeps it's value until the session ends.
Comment
Watch Question

Systems architect
Top Expert 2006
Commented:

Here the JavaScript version:


< script> 
var sesCookie = window.location.search.match(/[\?\&]wordpress_sourcetagji\=([^\&]*)/); 
if(sesCookie){ 
	document.cookie="wordpress_sourcetagji="+sesCookie[1]+";domain=.yourdomain.com;path=/;"; 
} 
< /script>
Jon ImmsWeb Developer

Author

Commented:
Awesome!! Thank You
ZvonkoSystems architect
Top Expert 2006

You are welcome  :  )