Unobtrusive Javascript based login window

Login window which appears on top of the content.

Login functionality is one of the gates to the members area. It should be provided in very accessible and clear form. I think that the best solution is to display a form on top of existing page, send the login request with automatically forward the action to the desired one.

The example uses Prototype and PHP, but it shouldn't be complicated to rewrite it for other software.

I've used this functionality on William Baker's B*Boy website which I had honour to build with Hatch recently.

I will show the details of the frontend part. In the backend I will refer to the magic User class which will contain a User::signin($lo­gin,$password) method. To simplify the code login div and form will be in DOM all the time (just hidden).

Login Form

This login form could be created by JavaScript to obtain full „unobtrusiveness“, if you want me to write the code, I'll do it later. This should be clearer.

<div id='generic_login_div' class='hidden'>
  <form id='generic_login_form' action='/login' action='post'>
    <h3>Login</h3>
    <p class='form-row'>
      <label for='username'>username:</label>
      <input type='text' name='username' id='username'/>
    </p>
    <p class='form-row'>
      <label for='password'>password:</label>
      <input type='password' name='password' id='password'/>
    </p>
    <p class='submit-row'>
      <input type='submit' value='login'/>
      <a onclick='hideLogin()'>Cancel</a>
    </p>
  </form>
</div>

One has to have a similar login form displayed on /login. It will be displayed for non Javascript users. It may be exactly the same code (just remove class hidden).

It's necessary to hide the div element using CSS.

/* Hide all elements contains class "hidden" */
.hidden { display: none; }
/* Style the div */
#generic_login_div {
  /* Place the login div on top of the page */
  z-index: 101;
  /* Define the position (i.e. center top) */
  position: absolute;
  width: 300px;
  top: 0;
  left: 50%;
  margin-left: -150px;
  /* Some important styling */
  background: white;
  border: 1px solid black;
}

There is a need to have functions to show and hide the div. I will use the Scriptaculous, but certainly $(el).show() or hide is enough

function showLogin() {
  if ($('generic_login_div').hasClassName('hidden')) {
    $('generic_login_div').hide();
    new Effect.Appear('generic_login_div');
    $('generic_login_div').removeClassName('hidden');
  }
}
function hideLogin() {
  if (!$('generic_login_div').hasClassName('hidden')) {
    new Effect.Fade('generic_login_div',{
      afterFinish: function () {
        $('generic_login_div').addClassName('hidden');
      }
    });
    $('generic_login_div').removeClassName('hidden');
  }
}

At the moment it's enough to just call the showLogin() function form any link. The form will be send to /login. It may be done like that:

<a href='/login' onclick='showLogin();return false;'>Login</a>

The login script could be written like that:

if (User::signin($_POST['username'],$_POST['password'])) {
  // startLabel: LoinSuccess
  $_SESSION['success'] = 'Welcome again';
  header('Location: /dashboard'); // redirect to default location
  // endLabel
} else {
  $_SESSION['error'] = 'Wrong login or password';
  header('Location: /login'); // display login page with an error
}

Redirect to current page

The login functionality works. But the page which is displayed afterwards is always a dashboard. To add the redirection I'll use sessions.

Every page has to save it's location:

$_SESSION['last_location'] = '/downloads'; // save current page location in our example (/downloads)

The login script has to read it and redirect using this value

// startLabel: loginSuccess
$_SESSION['success'] = 'Welcome again';
$redirect = (array_key_exists('last_location')) ? $_SESSION['last_location'] : '/dashboard';
header('Location: ' . $redirect); // redirect to last or default location
// endLabel

Good. Most users could end at this point. There is still no AJAX, but the solution is simple and unobtrusive. To put things a little bit further I'd like to tackle a more complicated solution.

Let's imagine we have more links to restricted content on the page. One is just ‚/login‘ – after succesfull login user stays on the page, the other is ‚/restricted_dow­nload‘ which should be displayed only for logged in users. I'd like to login a user and redirect him to the restricted page if login was successful.

To do it I will create a new anchor tag:

<a href='/restricted_download' class='login redirect'>restricted download</a>

And change the login one:

<a href='/login' class='login'>login</a>

To keep the code unobtrusive the /restricted_dow­nload script needs to display the login script for guests:

// set the 'last_location'
$_SESSION['last_location'] = '/restricted_download';
if (!$user->isAuthenticated()) {
  $_SESSION['notify'] = 'You need to be logged in to access this page';
  header('Location: /login');
}

Every page needs to be parsed to check if there is any anchor tag with class login. It has to be initiated inside the code:

<script type='text/javascript'>
Event.observe('window','load',function () { initLogins(); });
</script>

To find all anchor tags with login class I will use the $$ function which is returning array of DOM elements. These elements will be changed to use onclick action rather than href.

function initLogins() {
  $$('a.login').each( function (el) {
    if (el.hasClass('redirect')) el.redirect = el.href;
    else el.redirect = '';
    el.href = '#';
    Event.observe(el,'click', function () {
      // startLabelJSRedirectA
      showLoginWithRedirect(el.redirect);
      // endLabel
    });
  });
}

There is a need to send redirect to /login:

function showLoginWithRedirect( redirect ) {
  new Insertion.After($('generic_login_form'),"<input type='hidden' name='redirect' value='"+redirect+"'/>");
  showLogin();
}

And use it in login script:

// startLabel: loginSuccess
$_SESSION['success'] = 'Welcome again';
$redirect = (array_key_exists('last_location')) ? $_SESSION['last_location'] : '/dashboard';
// Add redirect from login form
if (!empty($_POST['redirect']) $redirect = $_POST['redirect'];
header('Location: ' . $redirect); // redirect to last or default location
// endLabel

This is full solution, but it still does need to reload the page after every login. Better attempt would be to use AJAX, which will return success in JSON and other functions will use this response and take further actions.

I'll write the AJAX solution in the next couple days as a new post. Please do check soon!

Happy Easter!

Links

  1. Prototype functions $$ each

Trackback URL for this post:

http://piotr.zalewa.info/trackback/49
from unobtrusive on 2008, May 23 - 04:08

Bookmarked your post over at Blog Bookmarker.com!

Comments

افلام اون لاين (not verified) 1970, January 1 - 00:00

thanks for the code man keep it on bro

Anonymous (not verified) 1970, January 1 - 00:00

Try away this effective way that accomplish a effortless rearrange telephone lookup so when to cell phone lookup come across away who is bringing up the rear with the intention of mobile phone number. And you be capable of as well throw away this cellular phone number lookup with the intention of carry out a phone lookup concerning with the intention of liar. In addition to still by means of a rearrange search be able to make the annul cellular phone method the superlative thing you know how to eternally get amazing done condition you feel about it in our day.

Vernadette (not verified) 1970, January 1 - 00:00

Thanks for sharing this. It's very informative and helpful. mayweather vs ortiz pacquiao vs marquez

Anonymous (not verified) 1970, January 1 - 00:00

Its ok for me , i like it Finpecia online valtrex online generic Propecia

dream vacation network (not verified) 1970, January 1 - 00:00

Thanks for the bunch of good resourceful site.I really appreciate your blog,you have done the great job.hey your blog design is very nice, clean and fresh and with updated content, make people feel peace and I always like browsing your site.

gucci sunglasses (not verified) 1970, January 1 - 00:00

I have to say, I dont know if its the clashing colours or the bad grammar, but this blog is hideous! I mean, I dont want to sound like a know-it-all or anything, but could you have possibly put a little bit more effort into this subject. Its really interesting, but you dont represent it well at all, man.

cheap john legend tickets (not verified) 1970, January 1 - 00:00

This is a topic of my interest. I love reading through your blog, I wanted to leave a little comment to support you and wish you a good continuation. Wishing you the best of luck for all your blogging efforts.

moulins à farine (not verified) 1970, January 1 - 00:00

I’ve seen it create division in senior teams when handled Alaska Halibut Fishing incorrectly and seen transformation happen when used elegantly. It’s all about the intention and skill of those who facilitate the process.

Dry Fruits (not verified) 1970, January 1 - 00:00

. Best regards.

procurement solutions (not verified) 1970, January 1 - 00:00

Most users could end at this point. There is still no AJAX, but the solution is simple and unobtrusive

Forfait iPhone (not verified) 1970, January 1 - 00:00

yes i confirm

bag factory (not verified) 1970, January 1 - 00:00

d the login request with automatically forward the action to the desired one.

Pharmacy technician training (not verified) 1970, January 1 - 00:00

I could not agree with you more. logins should be easy and straight-forward.

Guess online store (not verified) 1970, January 1 - 00:00

I had already downloadd it, so thanks for the show! http://www.bu­ycheapguess.org http://www.bu­ycheapguess.org

phuket villas (not verified) 1970, January 1 - 00:00

Great information, I have been looking for this kind of thing all day, thank you

Futon mattress (not verified) 1970, January 1 - 00:00

Some genuinely nice stuff on this internet site , I love it.

Carla (not verified) 1970, January 1 - 00:00

Great tutorial, i hope i will learn more from you and your posts!

human hair extensions (not verified) 1970, January 1 - 00:00
Excellent article that will provide the incentive and basis for my works. Thanks!
villaggi lazio (not verified) 1970, January 1 - 00:00

With opera 11?

mayweather vs ortiz tickets (not verified) 1970, January 1 - 00:00

I have a presentation incoming week, and I am on the lookout for such information.

free bets uk (not verified) 1970, January 1 - 00:00

Greetings I recently finished reading through your blog and I'm very impressed. I do have a couple questions for you personally however. Do you think you're thinking about doing a follow-up posting about this? Will you be going to keep bringing up-to-date as well?

college research paper (not verified) 1970, January 1 - 00:00

In my opinion it's really good platform, I mean Java of course!

tankini (not verified) 1970, January 1 - 00:00

You published a really important information! It really helped me in my work!

pellet progress machine (not verified) 1970, January 1 - 00:00

Yep… Tripped over this one myself. Goodbye restful evening.

افلام اون لاين (not verified) 1970, January 1 - 00:00

clearly written and good reminder about the multiple levels of undo – always handy I find.

sauna slabeste (not verified) 1970, January 1 - 00:00

For this kind of javascripts i installed mozilla addon noscripts.

Backlink List (not verified) 1970, January 1 - 00:00

This is really a great and interesting article.

rossetto rosso (not verified) 1970, January 1 - 00:00

Yeah, there is no doubt that blogging is a very powerful medium for activism, no matter the form. The ouster of the former Egyptian president began online.

Torrent sites (not verified) 1970, January 1 - 00:00

Useful tutorial, clearly written and good reminder about the multiple levels of undo – always handy I find.

luxury dog beds (not verified) 1970, January 1 - 00:00

I really need this login form sir. Thanks for posting about it.

freelancer (not verified) 1970, January 1 - 00:00

JavaScript is like something which always give me new ideas to comeback!

Series torrents (not verified) 1970, January 1 - 00:00

Thanks for give rails info … thanks many for solved my prob.. meet again…

crema viso (not verified) 1970, January 1 - 00:00

ah dimenticavo mettimi pure sto commento e fottitti tua madre :)

palette ombretti (not verified) 1970, January 1 - 00:00

non me ne fotte una minchia di quello che hai scritto basta che mi metti sto commento poi puoi anche andare a prendertelo nel deretano

custom thesis (not verified) 1970, January 1 - 00:00

Thanks for useful piece of code!

pandora (not verified) 1970, January 1 - 00:00

Amazing ring!! Maybe the photo makes it look so desirable, but definitely must have ring for a cocktail party.

clothing factory (not verified) 1970, January 1 - 00:00

i think it can be really helpful for all users of this application!

vessel faucet (not verified) 1970, January 1 - 00:00

Will this Javascript also work on Linux based programs?

term paper help (not verified) 1970, January 1 - 00:00

zoals je nu misschien al wel hebt gezien zijn er twee kampen voor kinderen in de leeftijd van 9 en 10 jaar, namelijk „Tijd voor Reclame“en „kamp Zweinstein“. Het reclame kamp is in Borculo, het andere kamp in Hoeven (Noord Brabant).

Villaggi Campania (not verified) 1970, January 1 - 00:00

Good Post

cosmetici (not verified) 1970, January 1 - 00:00

cosmetici

smalto per unghie (not verified) 1970, January 1 - 00:00

yes i confirm

lucidalabbra (not verified) 1970, January 1 - 00:00

on chrome 11 not work!

trucco occhi (not verified) 1970, January 1 - 00:00

jquery porting?

custom writing (not verified) 1970, January 1 - 00:00

You published a really important information! It really helped me in my work!

Implant Dentar (not verified) 1970, January 1 - 00:00

I generally don't use Javascript on my logins it is too easy to hack. and what if someone has JS turned off. Is the side compatible without Javascript? will they still be able to log in?

croisiere pas cher (not verified) 1970, January 1 - 00:00

I've been looking for this excellent blogs regarding this niche. Searching in Yahoo drove me here, I just found this type of satisfactory readings i was trying to find. I have to bookmark this internet site to avoid missing it again.

alanhawk (not verified) 1970, January 1 - 00:00

Yeah, there is no doubt that blogging is a very powerful medium for activism, no matter the form. The ouster of the former Egyptian president began online. business management school \ computer science school | criminal justice school

Mumbai Escorts (not verified) 1970, January 1 - 00:00

Thank U for most interesting post in this niche.

term paper (not verified) 1970, January 1 - 00:00

i think it can be really helpful for all users of this application!

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.