Navigetion

Sunday, August 5, 2012

Authentication With AJAX and PHP

THE IDEA

You want to ask the user to enter a name and password in a login form. If the name and password entered by the user matches with the contents in the server side script, your user should get a welcome message, otherwise a message should declare that they are an ‘Unauthorized user’.

Implementation

Let’s create an HTML file that displays two labels: ‘Enter your Name’ and ‘Enter your Password’ and two input text fields and a submit button and an empty div element. The HTML file should appear like this (place following code inside your body tag):



You can see that the HTML file contains the two input text fields that are assigned class names uname and passwd for the purpose of accessing them via jQuery code. Below the form is an empty div element of id message which we will be using for displaying the response generated by the server side script.

AJAX and jQuery code:

$(document).ready(function() {
 $('#submit').click(function () {
  var name = $('.uname').val();
  var pwd = $('.passwd').val();
  var data='uname='+name+'&password='+pwd;
  $.ajax({
   type:"POST",
   url:"logincheck.php",
   data:data,
   success:function(html) {
    $("#message").html(html);
   }
  });
  return false;
 });
});

The script file logincheck.php on the server validates the name and password entered by the user, and looks like this:

logincheck.php

$name = trim($_POST['uname']);
$pswd = trim($_POST['password']);
if(($name=="guest") && ($pswd=="jquery"))
  echo "Welcome ". $name;
else
  echo "Sorry you are not authorized";

And we are ready to go! Check your working AJAX Authentication application. Too sleepy to write got to go, knock me if you are stuck anywhere, bye bye :)...

4 comments:

  1. I would really admire the work and efforts you did to make this blog wonderful and spectacular thanks keep post I wanted to write a quick note to express my thanks. I’m really impressed by a blog unique and perfectly chosen and organized!

    ReplyDelete
    Replies
    1. Thanks, love all the support. Check out my new posts.

      Delete
  2. Thanks for sharing excellent informations. I’m impressed by the details that you’ve on this web site. I will come back soon.

    ReplyDelete
    Replies
    1. Thanks, love all the support. Check out my new posts.

      Delete