Method for over-riding various jQuery events if a global var is not set
Question by Dunhamzzz
I have various jQuery click and submit events on my site, but some of them I only want to activate if the user is logged in (yes I have all required server-side validation), if they are not logged in, I want a jQuery UI dialogue to pop up.
If the user is logged in the page will have a javascript variable set: with var uk = 'randomkey';
What is the best method for this? Off the top of my head some sort of global function which checks for user value and fires the dialogue and returns false? Or is there a neater/optimised way of doing it.
Answer by Richard Neil Ilagan
Since you say that you’re already performing server-side validation, I’d suggest that you take away all the JS behavior you want for logged-in users, and those for not-logged-in users to two separate JS files, and load the relevant one into the page before your server even flushes the HTML back to the browser.
Answer by Starx
It would be better if you would filter the elements while the page is loading, to avoid unauthorised access. Try to avoid complexity as much as possible.
But if you really need to do this, you can send a ajax request to detect if user is logged in (Relying on the client’s browser by setting class name is a bad idea, it can be easily tampered).
Just an example
$.post(
"apage.php",
{ action: 'checklogged' },
function(data) {
//if the response come as `no` and `yes`
if(data=='no') {
//dialogbox code
}
else {
var uk = 'randomkey';
}
}
);