0

Please help me to find a sutable solution for below in js:

1) I have a URL from referrer that contains two variables

2) I have to catch pdid and puid variables form URL and set cookies with name POKUPON_DID and POKUPON_UID and their values

3) The main problem that cookies are set to undefined if URL does not contain this variables. I need your help with corect IF statement. The code should preform only once and if variables in URL are exist...

function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

var $POKUPON_DID = getUrlVars()["pdid"];
var $POKUPON_UID = getUrlVars()["puid"];
 
if($POKUPON_DID != emty){
    
function setCookie(cname,cvalue,exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires=" + d.toGMTString();
    document.cookie = cname+"="+cvalue+"; "+expires;

}

setCookie("POKUPON_DID",$POKUPON_DID,30);
setCookie("POKUPON_UID",$POKUPON_UID,30);
}

Thank you a lot in advance!

1 Answers1

0

You need to be checking for undifiend read up on this: How to check for "undefined" in JavaScript?

function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}
function setCookie(cname,cvalue,exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires=" + d.toGMTString();
    document.cookie = cname+"="+cvalue+"; "+expires;

}

var $POKUPON_DID = getUrlVars()["pdid"];
var $POKUPON_UID = getUrlVars()["puid"];
 console.log($POKUPON_DID);
 console.log($POKUPON_UID);

if(typeof $POKUPON_DID != 'undefined'){
setCookie("POKUPON_DID",$POKUPON_DID,30);
setCookie("POKUPON_UID",$POKUPON_UID,30);
}
Community
  • 1
  • 1
vimes1984
  • 1,675
  • 2
  • 25
  • 54