Set a Cookie based on url Parameter

Programmermid picture Programmermid · Apr 22, 2015 · Viewed 22.5k times · Source

I need to set a cookie whenever a user clicks through one of our affiliate links and lands on our site with "src=uni" in the URL. The URLs will look something like this:

http://www.myadmin.com?src=uni&utm_source=uni&utm_content=[publisher_ID]

Function to create cookie:

 function SetCookie() {
            var url = window.location.href;
            if(url.indexOf('?src' + uni) = 1)
                document.cookie="QueryCookie";
    }

Can somebody help me by telling where I am going wrong in creating this Cookie based on query parameters?

Answer

bloodyKnuckles picture bloodyKnuckles · Apr 22, 2015

A few things here:

function SetCookie() {
    var url = window.location.search;
    if(url.indexOf('?src=uni') !== -1)
        document.cookie="src=uni";
}

1) Use location.search to narrow down your range, not necessary, but less room for error,

2) Use !== -1 to test the indexOf method. indexOf returns "-1" if it does not find a match. And "0" if it finds a match at the beginning of the string. The string is "zero indexed" which means the first character in the string is in position "0".

3) Add the equal sign = along with your parameter name: src=.

4) Also, use the string "uni" if that is what you're looking for, rather than a variable named uni. If "src" can be a variety of values, then we'll need to add some more logic to account for that.

5) And when assigning to document.cookie use key/value pairs as in: key=value.