Overview:
This document is useful for creating web application using AJAX. This document explain what is Ajax, how to use with sample source code in C#.net.
This document covers the following
1) How to create web application using Ajax
2) How to call server side method from JavaScript
3) How to fetch data from database without taking client side round trip
4) From where to download AJAX framework
Introduction:
ASP.NET AJAX is a framework for creating a new generation of more efficient, more interactive and highly-personalized Web application that work across most of browsers.
What you can do with ASP.NET AJAX:
ü Access remote services and data directly from the browser without writing complicated script.
ü Create next-generation interfaces with reusable AJAX components.
ü Enhance existing Web pages using powerful AJAX controls. Continue using Visual Studio 2005.
Download center
Sample Source code
In the Web application if we want to get data from the server we have to do server trip to execute code behind function that execute stored procedure/query to fetch/delete/update the data from the database.
server trip is always very heavy operation in the web application. Now using Ajax we can avoid client side server trip and without client side server trip we can get the data in the client side.
AJAX is nothing like magic; it is a way to call server side methods from JavaScript.
Ajax.NET is good for lightweight remote calls using JavaScript.
Let say you have a requirement where if you type any text in the text box corresponding data should display in the table, this is kind of searching related data as when you type any text in the text box.
Below I am giving one example code "How to fetch data from database using AJAX call"
Follow the steps to create Web Application
1) Create one Aspx page name "GetUser.aspx"
a) Create one private method in this page say "GetUsernameListFromDB"
private void GetUsernameListFromDB()
{
string conn = "Data Source= DBServer;Initial Catalog=DBNAme;
User Id= UID;Password= PWD";
//Get the request query
string whereCondition = Request["Condition"].ToString();
string sqlQuery = "select FName,Lname,DOB from Employee
where FName like '" + whereCondition + "%'";
DataSet ds = new DataSet();
ds = SqlHelper.ExecuteDataset(conn,CommandType.Text, sqlQuery);
StringBuilder strXml = new StringBuilder();
strXml.Append("<table border='1' width='100%'
height='100%' cellpadding='2' cellspacing='2'>");
strXml.Append("<tr bgcolor='skyblue'>
<td>First Name </td><td>Last Name</td>
<td>Date of Birth</td></tr>");
//Create Html Table runtime
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
strXml.Append("<tr>");
for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
{
strXml.Append("<td>" + ds.Tables[0].Rows[i][j].
ToString() + "</td>");
}
strXml.Append("</tr>");
}
strXml.Append("</table>");
// This is for to retain the value when page get referesh
Session["XMLData"] = strXml;
//write response data in the page
Response.Write(strXml);
}
b) Call above method in the page load event of "GetUser.aspx.cs" page
protected void Page_Load(object sender, EventArgs e)
{
GetUsernameListFromDB();
}
2) Create another Aspx page name "Default.aspx"
a) Screen shot
b) Design Source code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Getting Data from Database using AJAX Call</title>
</head>
<script>
var xmlHttp;
var requestURL = 'http://localhost/AjaxExample/GetUser.aspx?Condition=';
var is_ie = (navigator.userAgent.indexOf('MSIE') >= 0) ? 1 : 0;
var is_ie5 = (navigator.appVersion.indexOf("MSIE 5.5")!=-1) ? 1 : 0;
var is_opera
= ((navigator.userAgent.indexOf("Opera6")!=-1)
(navigator.userAgent.indexOf("Opera/6")!=-1)) ? 1 : 0;
//netscape, safari, mozilla behave the same???
var is_netscape
=(navigator.userAgent.indexOf('Netscape') >= 0) ? 1 : 0;
function Display_Data(strName)
{
if (strName.length > 0)
{
//Append the name to search for to the requestURL
var url = requestURL + strName;
//Create the xmlHttp object to use in the request //stateChangeHandler will fire when the state has changed, i.e. data is received back
// This is non-blocking (asynchronous)
xmlHttp = GetXmlHttpObject(stateChangeHandler);
//Send the xmlHttp get to the specified url
xmlHttp_Get(xmlHttp, url);
}
else
{
//Textbox blanked out, clear the results
document.getElementById('RelatedDataList').innerHTML = '';
}
}
//stateChangeHandler will fire when the state has changed, i.e. data is received back, This is non-blocking (asynchronous)
function stateChangeHandler()
{
//readyState of 4 or 'complete' represents that data has been returned
if (xmlHttp.readyState == 4 xmlHttp.readyState == 'complete')
{
//Gather the results from the callback
var str = xmlHttp.responseText;
//alert(str);
//Populate the innerHTML of the div with the results
if (document.getElementById)
{
//This indirecting writing into the panel require for IE
var t = document.createElement('div');
t.innerHTML = str;
document.getElementById('RelatedDataList').innerHTML = "";
document.getElementById('RelatedDataList').appendChild(t);
}
else if (document.all)
{
document.all['RelatedDataList'].innerHTML = xmlHttp.responseText;
}
else if (document.layers)
{
document.layers['RelatedDataList'].innerHTML = xmlHttp.responseText;
}
}
}
// XMLHttp send GET request
function xmlHttp_Get(xmlhttp, url)
{
xmlhttp.open('GET', url, true);
xmlhttp.send(null);
}
function GetXmlHttpObject(handler)
{
var objXmlHttp = null;
//Holds the local xmlHTTP object instance
//Depending on the browser, try to create the xmlHttp object
if (is_ie)
{
//The object to create depends on version of IE
//If it isn't ie5, then default to the Msxml2.XMLHTTP object
var strObjName = (is_ie5) ? 'Microsoft.XMLHTTP' : 'Msxml2.XMLHTTP';
// create the object
try{
objXmlHttp = new ActiveXObject(strObjName);
objXmlHttp.onreadystatechange = handler;
}
catch(e){
//Object creation errored
alert('IE detected, but object could not be created. Verify that
active scripting and activeX controls are enabled');
return;
}
}
else if (is_opera)
{
//Opera has some issues with xmlHttp object functionality
alert('Opera detected. The page may not behave as expected.');
return;
}
else
{
// Mozilla Netscape Safari
objXmlHttp = new XMLHttpRequest();
objXmlHttp.onload = handler;
objXmlHttp.onerror = handler;
}
//Return the instantiated object
return objXmlHttp;
}
function UseValue(strVal)
{
document.frmDefault.txtName.value = strVal;
}
</script>
<body>
<form name="frmDefault" id="Form1" runat="server">
<table border="0" cellpadding="4" cellspacing="0" id="Table2" >
<tr>
<td width="100">Name:</td>
<td>
<input type="text" name="txtName" id="txtName" autocomplete="off" onkeyup="Display_Data(txtName.value);">
</td>
</tr>
<tr>
<td width="100" valign="top">Related Data:</td>
<td>
<div id="RelatedDataList" runat="server"></div>
</td>
</tr>
</table>
</form>
</body>
</html>
c) Code behind (Default.aspx.cs)
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// This require when you need to persist the data after referesh
if (Session["XMLData"] != null)
{
RelatedDataList.InnerHtml = Session["XMLData"].ToString();
}
}
}
d) Run the application and type some text in the "Name" text box
As when you type any text in the "Name" text box without getting server trip for client it display filter data in to the screen.
How this page works internally
1) When you type any text into the textbox onkeyup events of textbox calls JavaScript function "Display_Data(txtName.value);" This function internally points to "GetUser.aspx" page in the form of http module 'http://localhost/AjaxExample/GetUser.aspx?Condition ='
2) And based on QueryString parameter "GetUser.aspx" page_Load calls perticular method "GetUsernameListFromDB()", This method take the parameter and get the data from database and generate html table structure on server side and return (html) result to page using "Response.write(strXml)"
3) Yes, It does server trip but it's happen parallel in server side it's not visible to client page, client page does not refresh in this whole process that why we can say without client side post back we can call code behind method using AJAX.
Limitations
Ø Input from devices such as microphones, webcams, and gamepads; output to devices like printers and portable gadgets.
Ø Playing music and sound effects.
Ø Adding buttons, toolbars, bookmarks, icons; changing browser behavior.
Ø Reading and writing files on the user's hard drive.
Ø Catching events such as shutdown initiation; changing preferences; popping up alerts; reading hardware information.
Ø Providing a full range of keyboard shortcuts while avoiding conflicts with the browser's own keyboard shortcuts.