views:

41

answers:

2

In a CMS I'm building I want to have my own javascript namespaced object $cms. This object should have a method/function hasIdentity that returns the status of whether the user is logged in.

Is there a way that I can have this method/function return the status without having to resort to either:

  • AJAX
  • a global var
  • or rewriting the following script from within PHP

This is what I have so var:

var $cms = {
    hasIdentity: function()
    {
        return /* the status provided by PHP */;
    }
};

It's a bit of a esthetic matter perhaps, but I don't want to resort to this:

// write this global var;
var $isLoggedIn = false;

var $cms = {
    hasIdentity: function()
    {
        return $isLoggedIn;
    }
};

Or this:

var $cms = {
    hasIdentity: function()
    {
        $isLoggedIn = this.do.some.ajax.call();
        return $isLoggedIn;
    }
};

I was maybe thinking more of a sort of OOP approach, something like constructing the $cms object by writing it from within PHP:

<script type="text/javascript">
  $cms = new $cms( <?php echo $loggedIn ? 'true', 'false' ?> );
</script>

Now, I believe I can't use the new keyword like that in Javascript, but I hope you catch my drift, and see where I want to go with this.

A: 

You could use a cookie. Set it from the PHP when user logs in and have the hasIdentity method read the cookie and return it's state. It's not the safest solution since cookies can be forged, but you're checking everything on the server side too anyway, right? :)

Marko
+2  A: 

You could also do:

$cms.isLoggedIn = <?php echo $loggedIn ? 'true', 'false' ?>;

That because your $cms object is not a constructor function. If it were, you would have been able to new it.

var CMS = function (loggedIn) {
    this.loggedIn = loggedIn;
};

CMS.prototype.hasIdentity = function () {
    return this.loggedIn;
};

$cms = new CMS(<?php echo $loggedIn ? 'true', 'false' ?>);
Ionuț G. Stan
That is exactly what I was looking for. Sweet! Thanks a lot.
fireeyedboy