0

How to get the value of a cookie in jquery. I want t be able to get the user_first_name and user_last_name from this cookie - {"user_first_name":["Raj Subscriber"],"user_last_name":["Chudasama"]}

function getCookieName(cname) {
    var name = cname + "=";
    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);
        }
    }
    return "";
}

I tried this:

 const userIsLoggedIn = getCookieName('tmm_user_data');
 const b = userIsLoggedIn.user_first_name[0];

AND THIS:

 const userIsLoggedIn = getCookieName('tmm_user_data');
 const b = userIsLoggedIn.user_first_name;

Both return undefined

Raj
  • 39
  • 6
  • Also, just FYI, jQuery is not what you need for this. jQuery is a framework primarily for working with the DOM. To get/set cookies you need to use plain JS. – Rory McCrossan Jan 29 '23 at 17:24

1 Answers1

0

Just in case you don't know. JS doesn't have a built-in function getCookieName(). You would be required to make it yourself.

Eg:

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

Then you can use the function getCookie(<name>) to access the desired one.