Sencha Inc. | HTML5 Apps

A Basic Login

Published Apr 19, 2008 | David Fitch | Tutorial | Easy
Last Updated Jul 11, 2011

This Tutorial is most relevant to Ext JS, 2.x, 3.x.

Entry Point

Let's assume the entry point to your application is index.asp, and it is structured as follows:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
	<head>
	<link rel="stylesheet" type="text/css" href="/igs/includes/ext/resources/css/ext-all.css">	
	<script type="text/javascript" src="/igs/includes/ext/adapter/ext/ext-base.js"></script>
	<script type="text/javascript" src="/igs/includes/ext/ext-all.js"></script>
	<script type="text/javascript" src="login.js"></script>	
	</head>
	<body></body>
</html>

Obviously, modify the paths to your EXT directory accordingly. See the source for Login.js below

Login.js

Next comes login.js. This guy handles all the heavy lifting, and for me, has all the pieces I was missing coming from a more traditional way of thinking about user authentication. It creates the form, renders it to a popup window, presents the window to the user, sends the submission via ajax, and handles the success and failure response depending on whether your user entered successful credentials.

Ext.onReady(function(){
    Ext.QuickTips.init();
 
	// Create a variable to hold our EXT Form Panel. 
	// Assign various config options as seen.	 
    var login = new Ext.FormPanel({ 
        labelWidth:80,
        url:'login.asp', 
        frame:true, 
        title:'Please Login', 
        defaultType:'textfield',
	monitorValid:true,
	// Specific attributes for the text fields for username / password. 
	// The "name" attribute defines the name of variables sent to the server.
        items:[{ 
                fieldLabel:'Username', 
                name:'loginUsername', 
                allowBlank:false 
            },{ 
                fieldLabel:'Password', 
                name:'loginPassword', 
                inputType:'password', 
                allowBlank:false 
            }],
 
	// All the magic happens after the user clicks the button     
        buttons:[{ 
                text:'Login',
                formBind: true,	 
                // Function that fires when user clicks the button 
                handler:function(){ 
                    login.getForm().submit({ 
                        method:'POST', 
                        waitTitle:'Connecting', 
                        waitMsg:'Sending data...',
 
			// Functions that fire (success or failure) when the server responds. 
			// The one that executes is determined by the 
			// response that comes from login.asp as seen below. The server would 
			// actually respond with valid JSON, 
			// something like: response.write "{ success: true}" or 
			// response.write "{ success: false, errors: { reason: 'Login failed. Try again.' }}" 
			// depending on the logic contained within your server script.
			// If a success occurs, the user is notified with an alert messagebox, 
			// and when they click "OK", they are redirected to whatever page
			// you define as redirect. 
 
                        success:function(){ 
                        	Ext.Msg.alert('Status', 'Login Successful!', function(btn, text){
				   if (btn == 'ok'){
		                        var redirect = 'test.asp'; 
		                        window.location = redirect;
                                   }
			        });
                        },
 
			// Failure function, see comment above re: success and failure. 
			// You can see here, if login fails, it throws a messagebox
			// at the user telling him / her as much.  
 
                        failure:function(form, action){ 
                            if(action.failureType == 'server'){ 
                                obj = Ext.util.JSON.decode(action.response.responseText); 
                                Ext.Msg.alert('Login Failed!', obj.errors.reason); 
                            }else{ 
                                Ext.Msg.alert('Warning!', 'Authentication server is unreachable : ' + action.response.responseText); 
                            } 
                            login.getForm().reset(); 
                        } 
                    }); 
                } 
            }] 
    });
 
 
	// This just creates a window to wrap the login form. 
	// The login object is passed to the items collection.       
    var win = new Ext.Window({
        layout:'fit',
        width:300,
        height:150,
        closable: false,
        resizable: false,
        plain: true,
        border: false,
        items: [login]
	});
	win.show();
});

Login.asp

Here is the server processing for your login. I'm going to paste the following overly simplistic code to show the responses that go back, and ultimately determine which function in login.js fires (success or failure). However, this is where you would make the call to the database with the username/password variables, do your authentication, and then send either of these responses depending on whether or not what the user provided a valid set of credentials.

<%
 
if request.form("loginUsername") = "f" then
	response.write "{ success: true}"
else
	response.write "{ success: false, errors: { reason: 'Login failed. Try again.' }}"
end if
 
%>

Login.cfm

<cfsetting showdebugoutput="No">
<cfif form.loginUsername eq "f">
    <cfset result = "{success: true}">
<cfelse>
    <cfset result="{success: false, errors: { reason: 'Login failed. Try again.' }}">
</cfif>
<cfoutput>#result#</cfoutput>

Login.jsp

<%@ page language="java" pageEncoding="UTF-8"%>
<%
	String result;
	String loginUsername = request.getParameter("loginUsername");
	if (null != loginUsername && loginUsername.length() > 0) {
		if (loginUsername.equals("f"))
			result = "{success:true}";
		else
			result = "{success:false,errors:{reason:'Login failed.Try again'}}";
 
	} else {
		result = "{success:false,errors:{reason:'Login failed.Try again'}}";
	}
%>
<%=result %>

Login.php

&lt;?php
$loginUsername = isset($_POST["loginUsername"]) ? $_POST["loginUsername"] : "";
 
if($loginUsername == "f"){
    echo "{success: true}";
} else {
    echo "{success: false, errors: { reason: 'Login failed. Try again.' }}";
}
?&gt;

Or, you can take advantage of PHP's associative arrays and json_encode function, and programatically render the JSON response. This can be helpful so you do not have to remember to escape certain character sequences or get lost in nested bracers if you are using more complex JSON.

&lt;?php
$loginUsername = isset($_POST["loginUsername"]) ? $_POST["loginUsername"] : "";
 
if($loginUsername == "f"){
    $result["success"] = true;
} else {
    $result["success"] = false;
    $result["errors"]["reason"] = "Login failed. Try again.";
}
echo json_encode($result);
?&gt;

Login.pl

#!/usr/bin/perl -w
use strict;
use CGI qw/:standard/;
my $login = param() ? param('loginUsername') : '';
print "Content-type: text/plain\n\n";
print $login eq "f" ? "{success: false, errors: { reason: 'Login failed. Try again.' }}" : "{success: true}";
exit;

You will notice a line in login.js that redirects to Test.asp if a successful login happens. This can obviously be whatever page your main application will be. In my situation, users can have any number of combinations of navigation options, so the next step would be to validate with whatever session management mecahanism you use, that the person accessing test.asp is authenticated to do so. Further, I would pull down whatever navigation options are assigned to that user and build my toolbar accordingly.

Share this post:
Leave a reply

Written by David Fitch

2 Comments

Amit

3 years ago

yes that was too good example ....but what if i have not used form instead i have used a grid.and posted data through proxy then how to get the posted json in jsp..

developer

3 years ago

I think is better to use
“Ext.Msg.confirm(‘Status’, ‘Login Successful!’, function(btn, text){ ... “
instead of
“Ext.Msg.alert(‘Status’, ‘Login Successful!’, function(btn, text){....”

Leave a comment:

Commenting is not available in this channel entry.