March 29, 2011

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';
        }
    }
);

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!