Thursday, 18 October 2007

Login using Ajax and PHP

In the previous lesson we have seen how to realize an user login using Ajax and Coldfusion. Today's lesson will explains how to realize the same action using Ajax and PHP.

Download this tutorial

Introduction
In the site root we have to create these file, index.php,login.php, config.php and a folder AJAX with ajax_framework.js.


The workflow is the same that I have explained in the previous lesson: the user submit an HTML form with the username (in this example is the email address) and password. The form action call a javascript function, login(), in the ajax_framework.js file. This function pass with URL variables the input data to login.php page that execute a query and verify if the user exist. If the user exist return the user name, else return 0. The function loginReply() take this value returned from login.php and show a message into a layer of index.php.


Step 1: the Login HTML Form
The first step is to create the HTML form. How you can see, the code below is indipendent from the server-side scripting language and can be used for example with Coldfusion, PHP and other languages. In the first row we will include ajax_framework.js that contains javascript functions to enable ajax functionalities (XMLHttpRequest and other functions, in this example the login() function):

<!-- Include AJAX Framework -->
<script src="ajax/ajax_framework.js" language="javascript"></script>

<!-- Show Message for AJAX response -->
<div id="login_response"></div>

<!-- Form: the action="javascript:login()"call the javascript function "login" into ajax_framework.js -->
<form action="javascript:login()" method="post">
<input name="emailLogin" type="text" id="emailLogin" value=""/>
<input name="pswLogin" type="password" id="pswLogin" value=""/>
<input type="submit" name="Submit" value="Login"/>
</form>


Step 2: the javascript function login()
In this lesson we have see how enable the XMLHTTPRequest. In ajax_framework.js file we have added this code:

/* ---------------------------- */
/* XMLHTTPRequest Enable */
/* ---------------------------- */
function createObject() {
var request_type;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
request_type = new ActiveXObject("Microsoft.XMLHTTP");
}else{
request_type = new XMLHttpRequest();
}
return request_type;
}

var http = createObject();


Now, in the same javascript file, we will add other lines of code for the function login():

/* -------------------------- */
/* LOGIN */
/* -------------------------- */
/* Required: var nocache is a random number to add to request. This value solve an Internet Explorer cache issue */
var nocache = 0;
function login() {
// Optional: Show a waiting message in the layer with ID ajax_response
document.getElementById('login_response').innerHTML = "Loading..."
// Required: verify that all fileds is not empty. Use encodeURI() to solve some issues about character encoding.
var email = encodeURI(document.getElementById('emailLogin').value);
var psw = encodeURI(document.getElementById('pswLogin').value);
// Set te random number to add to URL request
nocache = Math.random();
// Pass the login variables like URL variable
http.open('get', 'login.php?email='+email+'&psw='+psw+'&nocache = '+nocache);
http.onreadystatechange = loginReply;
http.send(null);
}
function loginReply() {
if(http.readyState == 4){
var response = http.responseText;
if(response == 0){
// if login fails
document.getElementById('login_response').innerHTML = 'Login failed! Verify user and password';
// else if login is ok show a message: "Welcome + the user name".
} else {
document.getElementById('login_response').innerHTML = 'Welcome'+response;
}
}
}


How you can see, the only change, respect to login() function of the previous tutorial with Coldfusion, is:

http.open('get', 'login.php?email='+email+'&psw='+psw+'&nocache = '+nocache);


...instead of:

http.open('get', 'login.cfm?email='+email+'&psw='+psw+'&nocache = '+nocache);


Step 3: login.php
In the previous step we have see how the login() function pass two variable (email and psw) to the page login.php, to execute a query into our database and verify that the user exists. This is the login.cfm page code:

<!-- Include Database connections info. -->
<?php include('config.php'); ?>

<!-- Verify if user exists for login -->
<?php
if(isset($_GET['email']) && isset($_GET['psw'])){

$email = $_GET['email'];
$psw = $_GET['psw'];

$getUser_sql = 'SELECT * FROM USER WHERE email="'. $email . '" AND psw = "' . $psw . '"';
$getUser = mysql_query($getUser_sql);
$getUser_result = mysql_fetch_assoc($getUser);
$getUser_RecordCount = mysql_num_rows($getUser);

if($getUser_RecordCount < 1){ echo '0';} else { echo $getUser_result['nick'];}
}


The tutorial is now ready to be tested in localhost server!
For info about PHP database connections and the file config.php included in the first row of login.php take a look to this post for other details.

No comments:

Post a Comment