views:

402

answers:

6

I want to check the login status of a user through an ajax request. Depending wether the user is logged in I want to display either the username/password input or the username. Currently the request is sent on body.onload and a prgoress indicator is shown until the response arrives. Is there a better way?


Let's assume that the requirements state that there should be no direct server side processing.

A: 

Why not check before the user is even given the html?

If you're just running static HTML w/ Javascript, I would suggest using JQuery and using the $(document).ready():

Steve g
A: 

Assuming that you really want to check the login status via ajax... No.

Zombies
+6  A: 

This sounds like an operation that should be done on the server first, before the page is rendered. If someone has javascript disabled, what would happen?

swilliams
It can be done, its just a little different from what has been the norm. If they don't have javascript enabled, they don't see anything (because no data gets loaded). But yeah you have to be very careful with this type of approach
Steve g
Yeah, red flags always go off in my head when anything related to security/logging in is done with javascript.
swilliams
+1 A security check that results in how the page is initially rendered would be best performed in the code-behind.
Kon
A: 

I think this should be possible, but it is not recommended. The correct thing to do is have the server fully determine the content of the page before it is even sent.

If you're being held up by slow image downloads or other non-HTML content, check out one of the various JavaScript libraries. I always recommend jQuery, which has the following syntax:

$(document).ready(function() {
  // The DOM is fully loaded now, but images might still be loading.
});
Neall
A: 

I believe that if you use inline javascript, it should be executed as soon as it's encountered:

<HTML><HEAD>...</HEAD>
<BODY>
<script>
document.write("This is written before anything else");
</script>
This come later.
</BODY>
</HTML>
James Curran
+1  A: 

If you don't want to depend on a toolkit, you can create your own DOMReady function that looks kinda like this:

/* Usage: DOMReady(ajaxFunc); */
function DOMReady(f) {
    if (!document.all) {
        document.addEventListener("DOMContentLoaded", f, false);
    } else {
        if (document.readystate == 'complete') { 
            window.setTimeout(f, 0);
        }
        else {
            //Add event to onload just if all else fails
            attachEvent(window, "load", f);
        }
    }
}

Or for a more complex solution: http://snipplr.com/view/6029/domreadyjs/

Eric Wendelin