Matt
Matt

Reputation: 5595

How can I check to see if the user is anonymous or logged in from javascript?

I would like to determine whether or not the user is logged in or if they're just anonymous from javascript...

I found this question, but it's php code and I wasn't sure if there is a session variable called logged_in that gets stored on login or if that was just something that person had implemented himself.

Anyone know how I can check to see if the user is logged in from javascript, possibly using ajax?

Edit: I'm running Asp.Net MVC, sorry should have specified

This is so that I can implement a client-side ajax login. When the page loads, I need to know if the user is logged in or not so I can implement something similar to an <asp:LoggedInView> control using jquery.

Thanks,
Matt

Upvotes: 10

Views: 26066

Answers (7)

Therichpost
Therichpost

Reputation: 1815

You can check with below code:

if(jQuery('body').hasClass('logged-in')) {
 // add your jquery code
 }

Upvotes: 0

Eddsters
Eddsters

Reputation: 497

Best Way in my opinion is to do it via ajax.

This will do it.

JS file...

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: 'check.php',
            success: function(d) { 
                if(d.r == "fail") {
                    window.location.href = d.url;
                } else {
                    console.log(d.msg);
                }
            }
        });

check.php

    if(!isset($_SESSION['loggedin'])){

        $response = array(
            'r' => 'fail',
            'url' => '/home.php'
        );
    } else {

        $response = array(
            'r' => 'success',
            'msg' => 'Logged in'
        );
    }

    echo json_encode($response);
    exit;

Upvotes: 1

kentaromiura
kentaromiura

Reputation: 6499

It hasn't any sense. If a user is logged in, you know it server-side. So you don't have to check if you're logged in client-side.

--EDIT :

After your clarification, I can only suggest to verify on the controller if the User is logged, if so you will show the normal view, otherwise you will show a different View.

-- EDIT added Aphorism:

Some people, when confronted with a problem, think “I know, I'll use ajax.” Now they have at least two problems

Upvotes: 1

xdevel2000
xdevel2000

Reputation: 21364

This is a solution usually implemented with server-side languages. With JS you, at least, could set in its client a cookie where store that information.

However with Ajax you should have a page (e.g. check_login.jsp/.apsx etc.) where to check if the user is logged (accessing to a DB, a Session variable etc.) and if so return back to JS (via JSON) that information and for example light a DIV with a green color...

So:

check_login.aspx--> return back the info via Response.Write("{user_logged:true}");

from login.aspx in your HTML code with JS you'll have an AJAX call where your xmlhttp is already an instance of XMLHttpRequest object...

var logged = JSON.parse(xmlhttp.responseText); // don't use eval
if(logged.user_logged)
document.getElementById("u_l").style.backgroundColor = "#00FF00";

Upvotes: 2

idrumgood
idrumgood

Reputation: 4924

[DISCLAIMER] Since I've been getting so many comments from people about this being 'bad practice', I'm just going to say this: It IS bad practice to do it this way, but we don't know what the original poster is intending to do. For all we know, he's done everything else 100% correct and secure, and was just asking if there was a way to get at it from javascript. What I have done below is provided my best idea for how to accomplish what he has asked. [/DISCLAIMER]

You can have your php, or whatever backend language you're using, set a cookie that you can then read with javascript.

document.cookie

simple as that. You'll have to search the cookie string for the name of your logged in cookie.

You can also use that to set a cookie and do your logging in through javascript (though probably not the best idea.)

See here for a quick overview of javascript cookie access.

[edit]

To address the issue of a client script having access to session information, and the possible use of ajax suggested in the original question:

Yes, an ajax call would be a very easy way to check this. I'm more of a jQuery guy, so my ajax experience lies there, but basically, you'd do an ajax call to your backend function, and that backend function just checks the 'loggedin' session variable, returning a true or false.

Also, since you now mentioned that you're using jQuery, see this page for easy jQuery cookie access. [/edit]

Upvotes: 7

Makram Saleh
Makram Saleh

Reputation: 8701

You can't read session saved data from JavaScript.

An easy way to do it is to create a JS var from PHP (easier than cookies solution), like this:

if ($_SESSION['logged_in'] == 1) {
    echo '<script type="text/javascript">var logged_in=true;</script>';
} else {
    echo '<script type="text/javascript">var logged_in=false;</script>';
}

Then the JS will simply check the native logged_in var to see if the user is logged in.

<script type="text/javascript">
    if (logged_in) {
        alert("My user is logged in!");
    }
</script>

Upvotes: 11

Alsciende
Alsciende

Reputation: 26971

You can parse document.cookie.

Upvotes: 0

Related Questions