Introduction
AJAX is an acronym that stands for Asynchronous JavaScript and XML. You see AJAX used every where now. Google is an example. It is just the process of making an out - of - band call (e.g., not with the normal page POST / RELOAD cycle) to some external resource, getting back the result either synchronously or asynchronously, and updating the content of the page that initiated the call, usually using client-side HTML DOM methods.
In this article, I will show you how to use AJAX to display a
DataGrid
dynamically. I assume that you know how to use Visual Studio to create web pages and HTML forms. Actually, I was given this daunting task of converting existing applications in our company to use AJAX. So, I had to find a way to do it using the same page instead of creating a new page for every page which had to use AJAX.The Steps
- Create the client page
- Add the JavaScript code
- Create the code remote .aspx page
Step 1
Open Visual Studio and create a new project. I used the name ajax. By default, Visual Studio creates a pageWebapplication1.aspx.Note that I am using C# as the code-behind. Rename webapplication1.aspx to ajax.aspx.
Step 2
Drag and drop a
DataGrid
control from the web forms toolbox on to the page. Give the DataGrid
an ID ofdgView
. Drag and drop an HTML text field from the HTML toolbox. Give it the name txtSearch
. Drag and drop an HTML button from the HTML toolbox. Name it btnSubmit
. In the HTML view, add the div
tag which is used to show the populated data, any where after the form fields
Collapse | Copy Code
<div id="datagrid"></div>
Step 3
And now comes the JavaScript code, the code is shown below. Don’t worry, I will explain how each function works. Add this code to the top of the page. Well, this code is the bread and butter of this script :).
Collapse | Copy Code
<script >
var xmlHttp;
var requestURL = ''http://localhost/ajax/ajax.aspx'';
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;
var is_netscape = (navigator.userAgent.indexOf(''Netscape'') >= 0) ? 1 : 0;
function show_data(str)
{
var url = requestURL;
xmlHttp = GetXmlHttpObject(ChangeHandler);
var params = formData2QueryString(this.document.forms[0]);
url += "&query=str;
xmlHttp_Get(xmlHttp, url);
}
function ChangeHandler()
{
if (xmlHttp.readyState == 4 ||
xmlHttp.readyState == ''complete''){
//get the results from the callback
var str = xmlHttp.responseText;
//populate the innerHTML of the div with the results
document.getElementById(‘datagrid’).innerHTML = str;
}
else
{
document.getElementById(''datagrid'').innerHTML =
"<table><tr><td width=''28''><img " +
"src=''images/waiting6.gif'' ></td><td " +
"valign=''middle''><b>Your record is loading" +
" please wait</b></td></tr></table>";
}
}
function xmlHttp_Get(xmlhttp, url)
{
xmlhttp.open(''GET'', url, true);
xmlhttp.send(null);
}
function GetXmlHttpObject(handler) {
var objXmlHttp = null;//Create the local xmlHTTP object instance
//Create the xmlHttp object depending on the browser
if (is_ie){
//if not IE default to Msxml2
var strObjName = (is_ie5) ? ''Microsoft.XMLHTTP'' :
''Msxml2.XMLHTTP'';
//Create the object
try{
objXmlHttp = new ActiveXObject(strObjName);
objXmlHttp.onreadystatechange = handler;
}
catch(e){
//Object creation error
alert(''Object cannot be created'');
return;
}
}
else if (is_opera){
alert(''Opera browser'');
return;
}
else{
// other browsers eg mozilla , netscape and safari
objXmlHttp = new XMLHttpRequest();
objXmlHttp.onload = handler;
objXmlHttp.onerror = handler;
}
//Return the instantiated object
return objXmlHttp;
}
</script>
- The function
GetXmlHttpObject()
checks the browser type and instantiates theXMLHttp
object. - The function
xmlHttp_Get
uses the GET method to send requests to the remote script. - The function
ChangeHandler()
checks for the data processing, and if it receives the data, it populates the data on the client page. - The function
show_data()
is the function we call to get the page results. You have to add theOnClick
event in the buttononCLick="javascript:show_data('''')"
Be sure to update the
requestURL
variable with the path that you will be accessing the aspx file from.
The complete code listing looks like this
Collapse | Copy Code
<%@ Page language="c#" Codebehind="ajax.aspx.cs"
AutoEventWireup="false" Inherits="ajax.ajax" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>Reader</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema"
content="http://schemas.microsoft.com/intellisense/ie5">
<script>
var xmlHttp;
var requestURL = ''http://localhost/ajax/ajax.aspx'';
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;
var is_netscape = (navigator.userAgent.indexOf(''Netscape'') >= 0) ? 1 : 0;
function show_data(str)
{
var url = requestURL;
xmlHttp = GetXmlHttpObject(ChangeHandler);
var params = formData2QueryString(this.document.forms[0]);
url += "&query="+this.document.forms[0].txtSearch.value;
xmlHttp_Get(xmlHttp, url);
}
function ChangeHandler()
{
if (xmlHttp.readyState == 4 ||
xmlHttp.readyState == ''complete''){
//get the results from the callback
var str = xmlHttp.responseText;
//populate the innerHTML of the div with the results
document.getElementById(''nameList'').innerHTML = str;
}
else
{
document.getElementById(''datagrid'').innerHTML =
"<table><tr><td width=''28''><img " +
"src=''images/waiting6.gif'' ></td><td " +
"valign=''middle''><b>Your record is loading " +
"please wait</b></td></tr></table>";
}
}
function xmlHttp_Get(xmlhttp, url)
{
xmlhttp.open(''GET'', url, true);
xmlhttp.send(null);
}
function GetXmlHttpObject(handler) {
var objXmlHttp = null;
//Create the local xmlHTTP object instance
//Create the xmlHttp object depending on the browser
if (is_ie){
//if not IE default to Msxml2
var strObjName = (is_ie5) ? ''Microsoft.XMLHTTP'' :
''Msxml2.XMLHTTP'';
//Create the object
try{
objXmlHttp = new ActiveXObject(strObjName);
objXmlHttp.onreadystatechange = handler;
}
catch(e){
//Object creation errore
alert(''Object cannot be created verify if ' +
'Active scripting and activeX controls are enabled'');
return;
}
}
else if (is_opera){
alert(''Opera browser'');
return;
}
else{
// other browsers eg mozilla , netscape and safari
objXmlHttp = new XMLHttpRequest();
objXmlHttp.onload = handler;
objXmlHttp.onerror = handler;
}
//Return the instantiated object
return objXmlHttp;
}
</script>
</HEAD>
<body MS_POSITIONING="GridLayout">
<form id="Form1" method="post" runat="server">
<asp:DataGrid id="dgView"
style="Z-INDEX: 101; LEFT: 144px; POSITION: absolute; TOP: 136px"
runat="server" Width="520px"></asp:DataGrid>
<input type="text" name="txtSearch">
<input type="button"
onCLick="javascript:show_data('''')" name="btnSubmit">
</form>
</body>
</HTML>
Step 4
Adding the remote script. Go to the code behind of the aspx page. This is the what my code listing looks like:
Collapse | Copy Code
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
namespace ajax
{
/// <summary>
/// Summary description for Reader.
/// </summary>
public class ajax : System.Web.UI.Page
{
protected System.Web.UI.WebControls.DataGrid dgView;
protected System.Web.UI.WebControls.Button Button1;
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
if(Request.QueryString["query"] != null)
{
bind();
}
}
private void bind()
{
//connection string to connect to the server
string ConnStr = "Server=servername;Database" +
"=databasename;UID=UID;PWD=password;";
SqlConnection sqlConn = new SqlConnection(ConnStr);
string query = "select * from table where text " +
"like ''%"+Request.QueryString["query"]+"%''";
SqlCommand sqlComm = new SqlCommand(query,sqlConn);
sqlComm.CommandType=CommandType.StoredProcedure;
sqlConn.Open();
SqlDataReader sqlReader;
sqlReader = sqlComm.ExecuteReader();
dgView.DataSource = sqlReader;
dgView.DataBind();
System.IO.StringWriter oStringWriter =
new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter =
new System.Web.UI.HtmlTextWriter(oStringWriter);
dgView.RenderControl(oHtmlTextWriter);
Response.Write(oHtmlTextWriter);
Response.End();
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by
// the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
}
}
No comments:
Post a Comment