Adsence750x90

Showing posts with label AJAX. Show all posts
Showing posts with label AJAX. Show all posts

Tuesday, February 1, 2011

Checking Username Availability using ASP.net AJAX

Checking username in user registration page is common thing in these days. Now we can check how to this using AJAX., ie Check username availability without postback. To achieve this you need to know about Ajax. Ajax is Asynchronous JavaScript and XML. AJAX is the art of exchanging data with a server, and update parts of a web page - without reloading the whole page [more].

Here I use two Class files and one Generic handler page to simplify code.

1: AjaxHelper
2: DataBaseHelper
3: Handler.ashx


Do not get confused, Client side javascript communicating sever with the help of Handler file, ie we send request to handler file, In the Handler file we create one instance of AjaxHelper Class and communicate with database with the help of DataBaseHelper Class


First we can check the sample images



User in Database








Now we can check how to send request to Handler Page, ie we do ajax calls to server, see the script below


Above we requested the handler file, Now we are going to check what handler file do when a request come from the client side.
first handler file check the query string. after create an instance of AjaxHelper class, it contain one boolean function called CheckUserNameAvailable(stirng username). if the value of CheckUserNameAvailable is true, it send response as "Available" else it send "Not Available".
public void ProcessRequest(HttpContext context)
    {
        HttpRequest request = context.Request;
        HttpResponse response = context.Response;
        if (!string.IsNullOrEmpty(request.QueryString["uname"]))
        {
            AjaxHelper ajaxHelper = new AjaxHelper();
            bool available = ajaxHelper.CheckUserNameAvailable(request.QueryString["uname"]);
            if (available)
            {
                response.Write("
Username Available
"); } else { response.Write("
Username Not Available
"); } } }

Next is what is happening AjaxHelper Class, here is do not use any store procedure, if you need you can use SP. I already mentioned that this class contain only one method, public bool CheckUserNameAvailable(string username)
in this class I select the users in usertable which username is equal to requested username.
public class AjaxHelper
{
    public AjaxHelper()
    {
    }
    public bool CheckUserNameAvailable(string username)
    {
        DataBaseHelper DBHelper = new DataBaseHelper();
        string cmdString = string.Format("SELECT username FROM usertable  WHERE username ='{0}'", username);
        string user = Convert.ToString(DBHelper.ExecuteScalar(cmdString));
        if (string.IsNullOrEmpty(user))
            return true;
        else
            return false;
    }
}


Check the DataBaseHelper Class, in DataBaseHelper class we read connection string form web.config file. then create sql connection, set sql command object, open sql connection, execute sql command, close sql connection, dispose command and connection.

public class DataBaseHelper
{
    SqlConnection con;
    SqlCommand cmd;

    public DataBaseHelper()
    {
    }
    public object ExecuteScalar(string commandText)
    {
        con = Provider.GetConnection();
        cmd = new SqlCommand(commandText, con);
        con.Open();
        try
        {
            return cmd.ExecuteScalar();
        }
        catch
        { throw; }
        finally
        {
            cmd.Dispose();
            con.Close();
            con.Dispose();
        }
    }
}




public class Provider
{
    public static SqlConnection GetConnection()
    {
        return new SqlConnection(ConfigurationManager.AppSettings["sqlConn"]);
    }
}


Connection string in Web.Config

    
  

Download source username availability in asp.net Ajax

Monday, May 5, 2008

AJAX DropDownList using UpdatePanel in C# and ASP.NET

Simple ASP.NET AJAX DropDownList USING UpdatePanel In C# ASP.NET 2005

Replace all "(" with '<' and also ")" with '>"

You can download AJAX controls in asp.net or From AJAX CONTROLS . Ajax stands for Asynchronous Javascript And XML. Here am going to bind data form database using AJAX UpdatePanel, and Binding city state and country for respected DropDownList.
As usual u can bind country DropDownList

C# code for Country DropDownList


protected void Page_Load(object sender, EventArgs e)
{

if (!IsPostBack)
{
SqlConnection con = new SqlConnection("Data Source=SERVER; Integrated Security=SSPI;persist security info=True;Initial Catalog=DBNAME;");
SqlCommand cmd = new SqlCommand("SELECT CountryName,CountryId FROM CountryTable", con);
DataTable dt = new DataTable();
con.Open();
SqlDataAdapter adptr = new SqlDataAdapter(cmd);
adptr.Fill(dt);
con.Close();
if (dt.Rows.Count > 0)
{
ddlCountry.Items.Clear();
ddlCountry.Items.Add("SELECT");
foreach (DataRow drow in dt.Rows)
{
ListItem lst = new ListItem();
lst.Value = drow[1].ToString();
lst.Text = drow[0].ToString();
ddlCountry.Items.Add(lst);
}
}
}

}

protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlCountry.SelectedValue.ToString() != "SELECT")
{
SqlConnection con = new SqlConnection("Data Source=SERVER; Integrated Security=SSPI;persist security info=True;Initial Catalog=DBNAME;");
SqlCommand cmd = new SqlCommand(string.Format("SELECT StateName,StateId FROM StateTable WHERE CountryId='{0}'", ddlCountry.SelectedValue.ToString()), con);
DataTable dt = new DataTable();
con.Open();
SqlDataAdapter adptr = new SqlDataAdapter(cmd);
adptr.Fill(dt);
con.Close();
if (dt.Rows.Count > 0)
{
ddlState.Items.Clear();
ddlState.Items.Add("SELECT");
foreach (DataRow drow in dt.Rows)
{
ListItem lst = new ListItem();
lst.Value = drow[1].ToString();
lst.Text = drow[0].ToString();
ddlState.Items.Add(lst);
}
}
}
}
HTML code

(asp:dropdownlist id="ddlCountry" runat="server" onselectedindexchanged="ddlCountry_SelectedIndexChanged" autopostback="True")(/asp:dropdownlist)
(br) (asp:updatepanel id="upnl" runat="server")(br) (contenttemplate)(br) (asp:dropdownlist id="ddlState" runat="server")(/asp:dropdownlist)(br) (/contenttemplate)(br) (triggers)(br) (asp:asyncpostbacktrigger controlid="ddlCountry")(br) (/asp:asyncpostbacktrigger)


Monday, April 7, 2008

ASP.NET AJAX DropDownList

ASP.NET AJAX DropDownList

html Code
@asp:dropdownlist id="ddlCountry" runat="server" onselectedindexchanged="ddlCountry_SelectedIndexChanged" autopostback="True"@@/asp:dropdownlist@
@asp:updatepanel id="upnl" runat="server"@
@contenttemplate@
@asp:dropdownlist id="ddlState" runat="server"@@/asp:dropdownlist@
@/contenttemplate@
@triggers@


@asp:asyncpostbacktrigger controlid="ddlCountry"@
@/asp:asyncpostbacktrigger@
@/triggers@



protected void Page_Load(object sender, EventArgs e)
{

if (!IsPostBack)
{
SqlConnection con = new SqlConnection("Data Source=SERVER; Integrated Security=SSPI;persist security info=True;Initial Catalog=DBNAME;");
SqlCommand cmd = new SqlCommand("SELECT CountryName,CountryId FROM CountryTable", con);
DataTable dt = new DataTable();
con.Open();
SqlDataAdapter adptr = new SqlDataAdapter(cmd);
adptr.Fill(dt);
con.Close();
if (dt.Rows.Count > 0)
{
ddlCountry.Items.Clear();
ddlCountry.Items.Add("SELECT");
foreach (DataRow drow in dt.Rows)
{
ListItem lst = new ListItem();
lst.Value = drow[1].ToString();
lst.Text = drow[0].ToString();
ddlCountry.Items.Add(lst);
}
}
}

}

protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlCountry.SelectedValue.ToString() != "SELECT")
{
SqlConnection con = new SqlConnection("Data Source=SERVER; Integrated Security=SSPI;persist security info=True;Initial Catalog=DBNAME;");
SqlCommand cmd = new SqlCommand(string.Format("SELECT StateName,StateId FROM StateTable WHERE CountryId='{0}'", ddlCountry.SelectedValue.ToString()), con);
DataTable dt = new DataTable();
con.Open();
SqlDataAdapter adptr = new SqlDataAdapter(cmd);
adptr.Fill(dt);
con.Close();
if (dt.Rows.Count > 0)
{
ddlState.Items.Clear();
ddlState.Items.Add("SELECT");
foreach (DataRow drow in dt.Rows)
{
ListItem lst = new ListItem();
lst.Value = drow[1].ToString();
lst.Text = drow[0].ToString();
ddlState.Items.Add(lst);
}
}
}
}

Tuesday, April 1, 2008

AJAX Example - request and response codes

The keystone of AJAX is the XMLHttpRequest object.

Different browsers use different methods to create the XMLHttpRequest object.

Internet Explorer uses an ActiveXObject,

while other browsers(Mozilla,Netscape,Opera..) uses the built-in JavaScript object called XMLHttpRequest.

To create this object, and deal with different browsers, we are going to use a "try and catch" statement.
between script tag u can write this code to detect browser
function ajaxFunction()
{
var xmlHttp;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
}

AJAX - Sending a Request to the Server

To send off a request to the server, we use the open() method and the send() method.

The open() method takes three arguments. The first argument defines which method to use when sending the request (GET or POST). The second argument specifies the URL of the server-side script. The third argument specifies that the request should be handled asynchronously. The send() method sends the request off to the server. If we assume that the HTML and ASP file are in the same directory, the code would be:

xmlHttp.open("GET","url",true);
xmlHttp.send(null);



xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
document.myForm.Form_elemet.value=xmlHttp.responseText;
}
}
xmlHttp.open("GET","default.aspx",true);
xmlHttp.send(null);

Source