Calling server side functions using AJAX
Today i am happened to learn about how to call server side functions using Ajax.
Steps needed to call server side function using ajax
1) Add Ajax.dll in references
2) Register the class in the page load using following code
private void Page_Load(object sender, System.EventArgs e)
{
//Register the class containing the server-side function
//we are interested in
Ajax.Utility.RegisterTypeForAjax(typeof(Sample));
}
3) Wrtie a server side function using following attribute
[Ajax.AjaxMethod(Ajax.HttpSessionStateRequirement.ReadWrite)]
public string GetClass(string fieldvalue)
{
int i=Convert.ToInt32(fieldvalue);
string s = "";
try
{
SqlConnection cn = new SqlConnection( @"server=servername;database=dbaname;User ID=userid;Password=password");
cn.Open();
SqlCommand cmd = new SqlCommand("Select * from tabalename where field name ="+ i, cn);
SqlDataReader dr=cmd.ExecuteReader();
while (dr.Read())
{
s = dr[0].ToString();
}
cn.Close();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
return s;
}
4)Add following java script in the .aspx
function GetClassData()
{
var txt=document.getElementById("txtclassid").value;
var response;
Sample.GetClass(txt,GetClass_CallBack);
}
function GetClass_CallBack(response)
{
var txt=document.getElementById("txtclassid").value;
if(response.value==txt)
{
alert('Already present in the database');
}
else
{
alert('Available');
}
}
5) Add following controls in the presentation layers
presentation layer
6) add the http handler in web.config
Steps needed to call server side function using ajax
1) Add Ajax.dll in references
2) Register the class in the page load using following code
private void Page_Load(object sender, System.EventArgs e)
{
//Register the class containing the server-side function
//we are interested in
Ajax.Utility.RegisterTypeForAjax(typeof(Sample));
}
3) Wrtie a server side function using following attribute
[Ajax.AjaxMethod(Ajax.HttpSessionStateRequirement.ReadWrite)]
public string GetClass(string fieldvalue)
{
int i=Convert.ToInt32(fieldvalue);
string s = "";
try
{
SqlConnection cn = new SqlConnection( @"server=servername;database=dbaname;User ID=userid;Password=password");
cn.Open();
SqlCommand cmd = new SqlCommand("Select * from tabalename where field name ="+ i, cn);
SqlDataReader dr=cmd.ExecuteReader();
while (dr.Read())
{
s = dr[0].ToString();
}
cn.Close();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
return s;
}
4)Add following java script in the .aspx
function GetClassData()
{
var txt=document.getElementById("txtclassid").value;
var response;
Sample.GetClass(txt,GetClass_CallBack);
}
function GetClass_CallBack(response)
{
var txt=document.getElementById("txtclassid").value;
if(response.value==txt)
{
alert('Already present in the database');
}
else
{
alert('Available');
}
}
5) Add following controls in the presentation layers
presentation layer
6) add the http handler in web.config
Comments