|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Announcements
Chapters
Services
Feature Zones
|
IntroductionThe latest buzz among web programmers is AJAX. Well, AJAX is nothing new, it has been around a while. It is nothing but remote scripting. 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 The Steps
Step 1Open Visual Studio and create a new project. I used the name ajax. By default, Visual Studio creates a page Webapplication1.aspx.Note that I am using C# as the code-behind. Rename webapplication1.aspx to ajax.aspx. Step 2Drag and drop a <div id="datagrid"></div>
Step 3And 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 :). <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>
Be sure to update the The complete code listing looks like this <%@ 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 4Adding the remote script. Go to the code behind of the aspx page. This is the what my code listing looks like: 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
}
}
The code is simple, there is nothing complex in it. In the page load event, I am checking whether the query string query is sent with the URL. If it is sent, I will call the function I bet this is very useful. You can use the same page to do all the AJAX calls. If you have done all the steps, run the page and insert something in the text field; if there is something in the database, it will return that to you as a
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||