McKin
McKin

Reputation: 5

Cookie a function via javascript or jQuery

Hello fellow stackoverflow. I'm up with a new question, here goes.

I would like to stuff the cookie of the following function in my ajax or javascript but I keep on failing to do , Here's my javascript function :

<script>
function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  } 
}

</script>

Now I would like it to appear like something like the below :-

setTimeout(function(){window.location = "https://www.something.com/index.html?affid=" + getQueryVariable("affid");}, 3000);

Is it possible to cookied the affid ??

So i would use something like this :

setTimeout(function(){window.location = "https://www.something.com/index.html?affid=" + getCookie("affid");}, 3000);

Upvotes: 0

Views: 56

Answers (2)

Aneesh Mohan
Aneesh Mohan

Reputation: 1087

Use the code below to retrieve the affid from cookie

 function getCookie(name) {
     var re = new RegExp(name + "=([^;]+)");
     var value = re.exec(document.cookie);
     return (value != null) ? unescape(value[1]) : null;
 }

Remember to set cookie named "affid" with the value on server side. If you want to set cookie from javascript you can make use of the code below.

function SetCookie(cookieName, cookieValue, nDays) {
    var today = new Date();
    var expire = new Date();
    if (nDays == null || nDays == 0) nDays = 1;
    expire.setTime(today.getTime() + 3600000 * 24 * nDays);
    document.cookie = cookieName + "=" + escape(cookieValue) + ";expires=" + expire.toGMTString();
}

Upvotes: 1

artm
artm

Reputation: 8584

Have a look at http://plugins.jquery.com/cookie/

It's a small simple cookie jQuery plugin. $.addCookie('... $.removeCookie(... etc.

Upvotes: 0

Related Questions