0

I have a cookie that I set the value in PHP, and I would like to the its value in javascript. I cant find any tutorials on this, I find tutorials that set and get values from either php or javascript, but i cant find a tutorial of setting a cookie in php and getting its value in JavaScript. The php cookie is workign i have echoed it.

PHP

setcookie($name, $pID, time() + (86400 * 30), "/");

Javascript

I tried this from W3 school but it doesnt work.

function displayA() {
        var name = "id=";
        var decodedCookie = decodeURIComponent(document.cookie);
        var ca = decodedCookie.split(';');
        for(var i = 0; i <ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') {
                c = c.substring(1);
            }
            if (c.indexOf(name) == 0) {
                return c.substring(name.length, c.length);
            }
        }
        alert(c);
    }
0

1 Answer 1

2

This is what I have been used in many projects, never had an issue. Check the jsfiddle for usage.

Also, use your browser (like Chrome) to check all saved cookies make sure you have the cookie before you read it.

EXP: https://jsfiddle.net/1t4q9ejx/

/*-----------------------------------------------------
            global function for Set/Get Cookie
------------------------------------------------------*/
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 + ";path=/";
}

function getCookie(name) {
  var value = "; " + document.cookie;
  var parts = value.split("; " + name + "=");
  if (parts.length == 2) return parts.pop().split(";").shift();
}
//set cookie
setCookie("selectedUnit", "10", 365);
//get cookie
let cookieUnits = getCookie("selectedUnit");
console.log('cookieUnits-->' + cookieUnits);

//list all cookies
function listCookies() {
  var theCookies = document.cookie.split(';');
  var aString = '';
  for (var i = 1; i <= theCookies.length; i++) {
    aString += i + ' ' + theCookies[i - 1] + "\n";
  }
  return aString;
}
console.log(listCookies());
Sign up to request clarification or add additional context in comments.

6 Comments

I set the cookie in PHP, I cant set the cookie in javascript, i need it set in php then used in javacript.
@LukeDS try the listCookies() function I just added, use console.log(listCookies()); to call it
@LukeDS use the getCookie(name) to get the cookie you want, I have php set cookies too.
Oh ok I will try it :)
It worked but can u explain to me what does the getCookie function is doing. step by step, i dont really get why set the var value to = ";" instead of just set to document.cookie, also what is the if statement doing? why is it checking if the length euqal 2?
|