Latest Post
Tampilkan postingan dengan label validation. Tampilkan semua postingan
Tampilkan postingan dengan label validation. Tampilkan semua postingan

Ajax login validation system in PHP using jQuery

Written By Unknown on Selasa, 21 Desember 2010 | 21.42

In this example, first of all we’ll validate the user login detail from ajax showing the messages with some animation. If authenticated, the user will be redirected to the secure page “secure.php”. If you’ll try to directly access “secure.php”, you can’t do that.


Now let’s look at the code how to do this,

HTML Code

< form method="post" action="" id="login_form" />
  < input name="username" type="text" id="username" value="" maxlength="20" />
  < input name="password" type="password" id="password" value="" maxlength="20" />
  < input name="Submit" type="submit" id="submit" value="Login" />
< /form >

As you can see in html code, we’ve created the form with id “login_form”.
And furthermore, the CSS code is same as the one available in the pervious post of checking user availability in ajax and php.

JavaScript Code for Ajax Login validation system in PHP


First of all we need to use the jQuery library in our code,

< script src="jquery.js" type="text/javascript" language="javascript"></script >

Now let’s look at the code in javaScript to call ajax and show the animated message with fading effects.

$("#login_form").submit(function()
{
        //remove all the class add the messagebox classes and start fading
        $("#msgbox").removeClass().addClass('messagebox').text('Validating....').fadeIn(1000);
        //check the username exists or not from ajax
        $.post("ajax_login.php",{ user_name:$('#username').val(),password:$('#password').val(),rand:Math.random() } ,function(data)
        {
          if(data=='yes') //if correct login detail
          {
                $("#msgbox").fadeTo(200,0.1,function()  //start fading the messagebox
                {
                  //add message and change the class of the box and start fading
                  $(this).html('Logging in.....').addClass('messageboxok').fadeTo(900,1,
                  function()
                  {
                     //redirect to secure page
                     document.location='secure.php';
                  });
                });
          }
          else
          {
                $("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
                {
                  //add message and change the class of the box and start fading
                  $(this).html('Your login detail sucks...').addClass('messageboxerror').fadeTo(900,1);
                });
          }
       });
       return false;//not to post the  form physically
});


in above code, where the user is validated, he’ll be logged into the “secure.php” using “document.location” in JavaScript.

$("#password").blur(function()
{
        $("#login_form").trigger('submit');
});

Well, as you can see above javaScript’s code, when focus is moved away from the password it also call the for sumit action. Basically whenever you hit tab button in password field, it starts validating the user detail using ajax.

PHP Code for Ajax Login validation system


First of all lets’s look at the code of the “ajax_login.php”.

//get the posted values
$user_name=htmlspecialchars($_POST['user_name'],ENT_QUOTES);
$pass=md5($_POST['password']); 

//now validating the username and password
$sql="SELECT user_name, password FROM tbl_user WHERE user_name='".$user_name."'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result); 

//if username exists
if(mysql_num_rows($result)>0)
{
        //compare the password
        if(strcmp($row['password'],$pass)==0)
        {
                echo "yes";
                //now set the session from here if needed
                $_SESSION['u_name']=$user_name;
        }
        else
                echo "no";
}
else
        echo "no"; //Invalid Login

As you can see above, the user login detial is validated from the database. If the user login detail doesn’t exists, it just returns the “no” values and if the user login detial does exists the it just return “yes” values with setting username in session variable.
Finally, let’s look at the code of secure.php

if(empty($_SESSION['u_name']))
  header("Location:index.html");
//if logout then destroy the session and redirect the user
if(isset($_GET['logout']))
{
  session_destroy();
  header("Location:index.html");
}
echo " <a href='secure.php?logout'><b>Logout<b></a> ";
echo " <div align='center'>You Are inside secured Page</a> ";

As you can see above the code of “secure.php” is simpleforward. If the user is not authenticated by session then he’ll be redirected to “index.html”. And there is link for “logout” in this page form where user can destroy the seession.


Implementation Guide:

To implement this code, dump the tbl_user “table” available in the zip file to your database and configure the database connection in “ajax_login.php.



Php function to validate two decimal places of a number

Written By Unknown on Selasa, 04 Mei 2010 | 01.11


If you are looking for the validation of a number which contains only two decimal places. Means you want to accept the values like 0.21 or 1.34 or 12.55 or 445.66 as a input and throw an error when somebody enters the number like 0.2 or 4.678 from a text box. Here is a simple function for you in PHP which validates the number weather it contains exactly two decimal places or not.

Function to validate two decimal places of a number in PHP


function validateTwoDecimals($number)
{
   if(ereg('^[0-9]+\.[0-9]{2}$', $number))
return true;
   else
return false;
}

Well let me explain the fairly simple regular expression inside the ereg() function of PHP.

^[0-9]+\.[0-9]{2}$

The hat(^) represents the start of the string and the [0-9]+ tells that there will be one or more digits at the starting of the the string. “‘\.” represents that there should be a period(.) after that and [0-9]{2} tells that after there should be exactly two digits after period and the dollar sign($) represents the end of the string.


Email address validation in PHP


you’ve been asking why this person has posted the same stuff which you can find easily in google. Ya you are right you can get lots of scripts but many of them are not useful for me so far. They just validate the email like “info@yahoo.com” but they didn’t validate the email address like “contact@roshanbh.com.np” or even the address like info@holmesglen.vic.edu.au“.


So I’m posting a email add validation function in PHP which validate those kind of address as well.

Function to validate email address in PHP

function validateEmail($email)
{
   if(eregi('^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z]{2,4}(\.[a-zA-Z]{2,3})?(\.[a-zA-Z]{2,3})?$', $email))
      return true;
   else
      return false;
}

Let’s see the explanation of the following regular expression to validate email address in php

^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z]{2,4}(\.[a-zA-Z]{2,3})?(\.[a-zA-Z]{2,3})?$

The “^” sign represents the start of the string.And, [a-zA-Z0-9._-]+ represents the first part of string before “@” sign can consists alpha bates, digits and “.,-” and “_” signs. After that “@” refers that this sign must exist. The next part is name of the domain and “[a-zA-Z0-9-]+” allow alpha bates, digits and “-” sign. After that period(.) should exist and validated by “\.“. And, the next string is TLD or ccTLd so can contain only two to four alphabates and validated by “[a-zA-Z]{2,4}“. The next part of expression “(\.[a-zA-Z]{2,3})?” refers that there will be another two or three alphabates after period(.) but this part is optional which is represented by “?” sign. And the last part is same as previous part and is optional as well.
Benefits:
Thus, this function validate the domain name that ends with .com or com.np or .vic.com.au . Furthermore, this function doesn’t accept the string like “info@homs.edu.” but I’ve some function which accepts the email which ends with period(.).


 
Support : Creating Website | Johny Template | Mas Template
Copyright © 2011. Kumpulan Kata Broadcast Blackberry - All Rights Reserved
Template Created by Creating Website Published by Mas Template
Proudly powered by Blogger