Saturday 14 May 2016

Implement jQuery AutoComplete TextBox from database using AJAX PageMethods in ASP.Net

<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.0.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/jquery-ui.min.js" type="text/javascript"></script>
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/themes/blitzer/jquery-ui.css"
    rel="Stylesheet" type="text/css" />
<script type="text/javascript">
    $(function () {
        $("[id$=txtSearch]").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: '<%=ResolveUrl("~/Default.aspx/GetCustomers") %>',
                    data: "{ 'prefix': '" + request.term + "'}",
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        response($.map(data.d, function (item) {
                            return {
                                label: item.split('-')[0],
                                val: item.split('-')[1]
                            }
                        }))
                    },
                    error: function (response) {
                        alert(response.responseText);
                    },
                    failure: function (response) {
                        alert(response.responseText);
                    }
                });
            },
            select: function (e, i) {
                $("[id$=hfCustomerId]").val(i.item.val);
            },
            minLength: 1
        });
    });  
</script>
Enter search term:
<asp:TextBox ID="txtSearch" runat="server" />
<asp:HiddenField ID="hfCustomerId" runat="server" />
<asp:Button ID="Button1" Text="Submit" runat="server" OnClick="Submit" />
 
 
Namespaces
You will need to import the following namespaces.
C#
using System.Web.Services;
using System.Configuration;
using System.Data.SqlClient;
 
VB.Net
Imports System.Web.Services
Imports System.Configuration
Imports System.Data.SqlClient
 
 
 The ASP.Net PageMethod
The following AJAX PageMethod accepts a parameter prefix and its value is used to find matching records from the Customers Table of the Northwind database.
The select query gets the Name and the ID of the customer that matches the prefix text.
The fetched records are processed and a Key Value Pair is created by appending the Id to the Name field in the following format {0}-{1} where is the Name {0} and {1} is the ID of the Customer.
 C#
[WebMethod]
public static string[] GetCustomers(string prefix)
{
    List<string> customers = new List<string>();
    using (SqlConnection conn = new SqlConnection())
    {
        conn.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.CommandText = "select ContactName, CustomerId from Customers where ContactName like @SearchText + '%'";
            cmd.Parameters.AddWithValue("@SearchText", prefix);
            cmd.Connection = conn;
            conn.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    customers.Add(string.Format("{0}-{1}", sdr["ContactName"], sdr["CustomerId"]));
                }
            }
            conn.Close();
        }
    }
    return customers.ToArray();
}
 
VB.Net
<WebMethod()>
Public Shared Function GetCustomers(prefix As StringAs String()
    Dim customers As New List(Of String)()
    Using conn As New SqlConnection()
        conn.ConnectionString = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Using cmd As New SqlCommand()
            cmd.CommandText = "select ContactName, CustomerId from Customers where ContactName like @SearchText + '%'"
            cmd.Parameters.AddWithValue("@SearchText", prefix)
            cmd.Connection = conn
            conn.Open()
            Using sdr As SqlDataReader = cmd.ExecuteReader()
                While sdr.Read()
                    customers.Add(String.Format("{0}-{1}", sdr("ContactName"), sdr("CustomerId")))
                End While
            End Using
            conn.Close()
        End Using
    End Using
    Return customers.ToArray()
End Function
 
 
Fetching the selected item on Server Side
The Key (Customer Name) and Value (Customer ID) can be fetched on server side inside the click event handler of the Button from the Request.Form collection as shown below.
 C#
protected void Submit(object sender, EventArgs e)
{
    string customerName = Request.Form[txtSearch.UniqueID];
    string customerId = Request.Form[hfCustomerId.UniqueID];
    ClientScript.RegisterStartupScript(this.GetType(), "alert""alert('Name: " + customerName + "\\nID: " + customerId +"');"true);
}
 
VB.Net
Protected Sub Submit(sender As Object, e As EventArgs)
    Dim customerName As String = Request.Form(txtSearch.UniqueID)
    Dim customerId As String = Request.Form(hfCustomerId.UniqueID)
    ClientScript.RegisterStartupScript(Me.GetType(), "alert""alert('Name: " & customerName & "\nID: " & customerId &"');"True)
End Sub
 
 

Saturday 10 October 2015

The registration form

Here is the registration form:

<form id='register' action='register.php' method='post'
    accept-charset='UTF-8'>
<fieldset >
<legend>Register</legend>
<input type='hidden' name='submitted' id='submitted' value='1'/>
<label for='name' >Your Full Name*: </label>
<input type='text' name='name' id='name' maxlength="50" />
<label for='email' >Email Address*:</label>
<input type='text' name='email' id='email' maxlength="50" />
<label for='username' >UserName*:</label>
<input type='text' name='username' id='username' maxlength="50" />
<label for='password' >Password*:</label>
<input type='password' name='password' id='password' maxlength="50" />
<input type='submit' name='Submit' value='Submit' />
</fieldset>
</form>
So, we have text fields for name, email and the password. Note that we are using the password widget for better usability.

Form validation

At this point it is a good idea to put some form validation code in place, so we make sure that we have all the data required to create the user account. We need to check if name and email, and password are filled in and that the email is in the proper format.
We can use the free JavaScript form validation script to add form validations quickly and easily, with lesser code.
Here is a sample JavaScript validation code to be used for the sample form we created earlier:
var frmvalidator  = new Validator("register");
frmvalidator.EnableOnPageErrorDisplay();
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("name","req","Please provide your name");
frmvalidator.addValidation("email","req","Please provide your email address");
frmvalidator.addValidation("email","email","Please provide a valid email address");
frmvalidator.addValidation("username","req","Please provide a username");
frmvalidator.addValidation("password","req","Please provide a password");
To be on the safe side, we will also have the same validations on the server side too. For server side validations, we will use the PHP form validation script

Handling the form submission

Now we have to handle the form data that is submitted.
Here is the sequence (see the file fg_membersite.php in the downloaded source):
function RegisterUser()
{
    if(!isset($_POST['submitted']))
    {
       return false;
    }
     
    $formvars = array();
     
    if(!$this->ValidateRegistrationSubmission())
    {
        return false;
    }
     
    $this->CollectRegistrationSubmission($formvars);
     
    if(!$this->SaveToDatabase($formvars))
    {
        return false;
    }
     
    if(!$this->SendUserConfirmationEmail($formvars))
    {
        return false;
    }
    $this->SendAdminIntimationEmail($formvars);
     
    return true;
}
First, we validate the form submission. Then we collect and ‘sanitize’ the form submission data (always do this before sending email, saving to database etc). The form submission is then saved to the database table. We send an email to the user requesting confirmation. Then we intimate the admin that a user has registered.

Saving the data in the database

Now that we gathered all the data, we need to store it into the database.
Here is how we save the form submission to the database.
function SaveToDatabase(&$formvars)
   {
       if(!$this->DBLogin())
       {
           $this->HandleError("Database login failed!");
           return false;
       }
       if(!$this->Ensuretable())
       {
           return false;
       }
       if(!$this->IsFieldUnique($formvars,'email'))
       {
           $this->HandleError("This email is already registered");
           return false;
       }
        
       if(!$this->IsFieldUnique($formvars,'username'))
       {
           $this->HandleError("This UserName is already used. Please try another username");
           return false;
       }       
       if(!$this->InsertIntoDB($formvars))
       {
           $this->HandleError("Inserting to Database failed!");
           return false;
       }
       return true;
   }
Note that you have configured the Database login details in the membersite_config.php file. Most of the cases, you can use “localhost” for database host.
After logging in, we make sure that the table is existing.(If not, the script will create the required table).
Then we make sure that the username and email are unique. If it is not unique, we return error back to the user.

The database table structure

This is the table structure. The CreateTable() function in the fg_membersite.php file creates the table. Here is the code:
function CreateTable()
{
    $qry = "Create Table $this->tablename (".
            "id_user INT NOT NULL AUTO_INCREMENT ,".
            "name VARCHAR( 128 ) NOT NULL ,".
            "email VARCHAR( 64 ) NOT NULL ,".
            "phone_number VARCHAR( 16 ) NOT NULL ,".
            "username VARCHAR( 16 ) NOT NULL ,".
            "password VARCHAR( 32 ) NOT NULL ,".
            "confirmcode VARCHAR(32) ,".
            "PRIMARY KEY ( id_user )".
            ")";
             
    if(!mysql_query($qry,$this->connection))
    {
        $this->HandleDBError("Error creating the table \nquery was\n $qry");
        return false;
    }
    return true;
}
The id_user field will contain the unique id of the user, and is also the primary key of the table. Notice that we allow 32 characters for the password field. We do this because, as an added security measure, we will store the password in the database encrypted using MD5. Please note that because MD5 is an one-way encryption method, we won’t be able to recover the password in case the user forgets it.

Inserting the registration to the table

Here is the code that we use to insert data into the database. We will have all our data available in the $formvars array.
function InsertIntoDB(&$formvars)
{
    $confirmcode = $this->MakeConfirmationMd5($formvars['email']);
    $insert_query = 'insert into '.$this->tablename.'(
            name,
            email,
            username,
            password,
            confirmcode
            )
            values
            (
            "' . $this->SanitizeForSQL($formvars['name']) . '",
            "' . $this->SanitizeForSQL($formvars['email']) . '",
            "' . $this->SanitizeForSQL($formvars['username']) . '",
            "' . md5($formvars['password']) . '",
            "' . $confirmcode . '"
            )';     
    if(!mysql_query( $insert_query ,$this->connection))
    {
        $this->HandleDBError("Error inserting data to the table\nquery:$insert_query");
        return false;
    }       
    return true;
}
Notice that we use PHP function md5() to encrypt the password before inserting it into the database.
Also, we make the unique confirmation code from the user’s email address.

Sending emails

Now that we have the registration in our database, we will send a confirmation email to the user. The user has to click a link in the confirmation email to complete the registration process.
function SendUserConfirmationEmail(&$formvars)
{
    $mailer = new PHPMailer();
     
    $mailer->CharSet = 'utf-8';
     
    $mailer->AddAddress($formvars['email'],$formvars['name']);
     
    $mailer->Subject = "Your registration with ".$this->sitename;
    $mailer->From = $this->GetFromAddress();       
     
    $confirmcode = urlencode($this->MakeConfirmationMd5($formvars['email']));
     
    $confirm_url = $this->GetAbsoluteURLFolder().'/confirmreg.php?code='.$confirmcode;
     
    $mailer->Body ="Hello ".$formvars['name']."\r\n\r\n".
    "Thanks for your registration with ".$this->sitename."\r\n".
    "Please click the link below to confirm your registration.\r\n".
    "$confirm_url\r\n".
    "\r\n".
    "Regards,\r\n".
    "Webmaster\r\n".
    $this->sitename;
    if(!$mailer->Send())
    {
        $this->HandleError("Failed sending registration confirmation email.");
        return false;
    }
    return true;
}
We use the free PHPMailer script to send the email.
Note that we make the confirmation URL point to confirmreg.php?code=XXXX (where XXXX is the confirmation code).

Making a login form using PHP


Here is the HTML code for the login form.

<form id='login' action='login.php' method='post' accept-charset='UTF-8'>
<fieldset >
<legend>Login</legend>
<input type='hidden' name='submitted' id='submitted' value='1'/>
<label for='username' >UserName*:</label>
<input type='text' name='username' id='username'  maxlength="50" />
<label for='password' >Password*:</label>
<input type='password' name='password' id='password' maxlength="50" />
<input type='submit' name='Submit' value='Submit' />
</fieldset>
</form>

Logging in

We verify the username and the password we received and then look up those in the database. Here is the code:
function Login()
{
    if(empty($_POST['username']))
    {
        $this->HandleError("UserName is empty!");
        return false;
    }
     
    if(empty($_POST['password']))
    {
        $this->HandleError("Password is empty!");
        return false;
    }
     
    $username = trim($_POST['username']);
    $password = trim($_POST['password']);
     
    if(!$this->CheckLoginInDB($username,$password))
    {
        return false;
    }
     
    session_start();
     
    $_SESSION[$this->GetLoginSessionVar()] = $username;
     
    return true;
}
In order to identify a user as authorized, we are going to check the database for his combination of username/password, and if a correct combination was entered, we set a session variable.
Here is the code to look up the username and password.
function CheckLoginInDB($username,$password)
{
    if(!$this->DBLogin())
    {
        $this->HandleError("Database login failed!");
        return false;
    }         
    $username = $this->SanitizeForSQL($username);
    $pwdmd5 = md5($password);
    $qry = "Select name, email from $this->tablename ".
        " where username='$username' and password='$pwdmd5' ".
        " and confirmcode='y'";
     
    $result = mysql_query($qry,$this->connection);
     
    if(!$result || mysql_num_rows($result) <= 0)
    {
        $this->HandleError("Error logging in. ".
            "The username or password does not match");
        return false;
    }
    return true;
}
Please notice that we must compare the value for the password from the database with the MD5 encrypted value of the password entered by the user. If the query returns a result, we set an “authorized” session variable, and then redirect to the protected content. If there are no rows with the entered data, we just redirect the user to the login form again.

Access controlled pages

For those pages that can only be accessed by registered members, we need to put a check on the top of the page.
Notice that we are setting an “authorized” session variable in the login code above. On top of pages we want to protect, we check for that session variable. If user is authorized, we show him the protected content, otherwise we direct him to the login form.
Include this sample piece of code on top of your protected pages:
<?PHP
require_once("./include/membersite_config.php");
if(!$fgmembersite->CheckLogin())
{
    $fgmembersite->RedirectToURL("login.php");
    exit;
}
?>
See the file: access-controlled.php in the downloaded code for an example.
Here is the CheckLogin() function code.
function CheckLogin()
{
     session_start();
     $sessionvar = $this->GetLoginSessionVar();
      
     if(empty($_SESSION[$sessionvar]))
     {
        return false;
     }
     return true;
}
These are the basics of creating a membership site. Now that you have the basic knowledge, you can experiment with it and add new features, such as a “Forgot password” page to allow the user to retrieve or change his password if he forgets it.







PHP login form