in php i would do
if (isset($_COOKIE[\'user\']) && $_COOKIE[\'user\'] == $valueFromDb)
echo \'logged\';
But in javascript how can
There is no reliable way to do this without making a request to the server, since the session might have expired on the server side. In one project, I do it the following, imperfect way:
checkAuth() {
var logged = (function() {
var isLogged = null;
$.ajax({
'async': false,
'global': false,
'url': '/user/isLogged/',
'success': function(resp) {
isLogged = (resp === "1");
}
});
return isLogged;
})();
return logged;
}
I say imperfect because it makes a synchronous request which temporarily locks up the browser. It does have an advantage in that checkAuth()
can be reliably called from any part of the client-side application since it forces the browser to wait for the result before continuing execution of the JS code, but that's about it.
The alternative, asynchronous (non-locking) approach would be to do something like this:
$.ajax({
'url': '/user/isLogged/',
'success': function(resp) {
if(resp === "1") {
// do your thing here, no need
// for async: false
}
}
});