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 type="text/javascript" src="Scripts/jquery-1.4.1.js"></script>
<script type="text/javascript" language="javascript">
var x = { s: { a: "1", b: "2", c: "3", d: "4" }, f: { a: "1", b: "2", c: "3", d: "4"} };
var xmlHttp;
//var requestURL = "http://localhost:52157/Default.aspx";
var requestURL = window.location.href;
debugger;
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) {
debugger;
var url = requestURL;
xmlHttp = GetXmlHttpObject(ChangeHandler);
// var params = formData2QueryString(this.document.forms[0]);
url += "?query=s";
xmlHttp_Get(xmlHttp, url);
}
function ChangeHandler() {
if (xmlHttp.readyState == 4 ||
xmlHttp.readyState == "complete") {
//get the results from the callback
var str = xmlHttp.responseText;
str = str.split('^')[0];
//populate the innerHTML of the div with the results
// document.getElementById("datagrid").innerHTML = str;
//var jsonArray = eval_global(str); //
// var jsonArray= eval(str.toString );
jsonArray = $.parseJSON(str);
// for (i in jsonArray) {
// alert(jsonArray[i]["name"]);
// }
obj = jsonArray;
tr1 = "<table><tr><th></th><th></th><th></th></tr>";
for (var i = 0; i < obj.length; i++) {
var tr = "<tr>";
var td1 = "<td>" + obj[i]["OrderNumber"] + "</td>";
var td2 = "<td>" + obj[i]["ReceiptNumber"] + "</td>";
var td3 = "<td>" + obj[i]["TenderType"] + "</td></tr>";
tr1 += tr + td1 + td2 + td3;
}
tr1 += "</table>";
document.getElementById("datagrid").innerHTML = tr1;
}
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;
<script type="text/javascript" src="Scripts/jquery-1.4.1.js"></script>
<script type="text/javascript" language="javascript">
var x = { s: { a: "1", b: "2", c: "3", d: "4" }, f: { a: "1", b: "2", c: "3", d: "4"} };
var xmlHttp;
//var requestURL = "http://localhost:52157/Default.aspx";
var requestURL = window.location.href;
debugger;
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) {
debugger;
var url = requestURL;
xmlHttp = GetXmlHttpObject(ChangeHandler);
// var params = formData2QueryString(this.document.forms[0]);
url += "?query=s";
xmlHttp_Get(xmlHttp, url);
}
function ChangeHandler() {
if (xmlHttp.readyState == 4 ||
xmlHttp.readyState == "complete") {
//get the results from the callback
var str = xmlHttp.responseText;
str = str.split('^')[0];
//populate the innerHTML of the div with the results
// document.getElementById("datagrid").innerHTML = str;
//var jsonArray = eval_global(str); //
// var jsonArray= eval(str.toString );
jsonArray = $.parseJSON(str);
// for (i in jsonArray) {
// alert(jsonArray[i]["name"]);
// }
obj = jsonArray;
tr1 = "<table><tr><th></th><th></th><th></th></tr>";
for (var i = 0; i < obj.length; i++) {
var tr = "<tr>";
var td1 = "<td>" + obj[i]["OrderNumber"] + "</td>";
var td2 = "<td>" + obj[i]["ReceiptNumber"] + "</td>";
var td3 = "<td>" + obj[i]["TenderType"] + "</td></tr>";
tr1 += tr + td1 + td2 + td3;
}
tr1 += "</table>";
document.getElementById("datagrid").innerHTML = tr1;
}
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>
</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.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Text;
namespace Ajax
{
public partial class JSON : System.Web.UI.Page
{
protected System.Web.UI.WebControls.DataGrid dgView;
protected System.Web.UI.WebControls.Button Button1;
string str = string.Empty;
private void Page_Load(object sender, System.EventArgs e)
{
//Put user code to initialize the page here
if (!string.IsNullOrEmpty(Request.QueryString["query"]))
{
bind();
}
}
private void bind()
{
//connection string to connect to the server
string ConnStr = "Server=##############;Database=############;UID=#####;PWD=#########;";
SqlConnection sqlConn = new SqlConnection(ConnStr);
string query = "select * from OP_OrderReceiptTenderTypes";
+ "like ''%" + Request.QueryString["query"] + "%''";
SqlCommand sqlComm = new SqlCommand(query, sqlConn);
sqlConn.Open();
DataTable dt = new DataTable();
using (SqlDataReader reader = sqlComm.ExecuteReader())
{
dt.Load(reader);
};
dgView = new DataGrid();
dgView.DataSource = dt;
dgView.DataBind();
Response.Write(GetJson(dt)+"^");
}
public string GetJson(DataTable dt)
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new
System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows =
new List<Dictionary<string, object>>();
Dictionary<string, object> row = null;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName.Trim(), dr[col]);
}
rows.Add(row);
}
return serializer.Serialize(rows);
}
}
}