Set the cookie based on the URL.

I need to set a cookie whenever a user clicks 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]

Cookie creation function:

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

      

Can someone please help me by telling me where am I going wrong creating this cookie based on request parameters?

+3


source to share


2 answers


Several 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 the range, not necessary, but less room for error,

2) Use !== -1

to test the method indexOf

. indexOf

returns "-1" if no match is found. And "0" if it finds a match at the beginning of the line. The string is "zero indexed", which means that the first character in the string is at position "0".



3) Add an equal sign =

, along with your name parameter: src=

.

4) Also use the string "uni" if that's what you are looking for, not a named variable uni

. If "src" can be multiple values, then we will need to add some more logic to account for this.

5) And when appointing document.cookie

use key / value pairs, as in: key=value

.

+2


source


The first thing you need to fix:

if(url.indexOf('?src' + uni) = 1)

      

should be (this checks that it exists at index 1):

if(url.indexOf('?src=' + uni) === 1)

      

or (this checks it out at all)

if(url.indexOf('?src=' + uni) !== -1)

      

Then you need to set src to uni and make it site-wide available:

document.cookie="src="+uni+"; path=/; domain=.myadmin.com";

      



Adding path = / and domain = .myadmin.com will allow you to access the cookie on all paths in that domain, and part of the domain will allow it to be accessible on all subdomains (e.g. www.myadmin.com as well as blog.myadmin. com, etc.)

so all together:

    function SetCookie() {
        var url = window.location.href;
        if(url.indexOf('?src='+uni) !== -1)
            document.cookie="src="+uni+"; path=/; domain=.myadmin.com";
    }

      


Here are some basic details:

http://www.w3schools.com/js/js_cookies.asp

Or in more detail, the exact documentation:

https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie

+1


source







All Articles