How To Create Ajax Based Search Page using xmlHTTP








<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Search.aspx.cs" Inherits="Search" %>

<!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>Untitled Page</title>

<script type="text/javascript">
//global variable for hold XMLHttpRequest Object
var xmlHttp;
//Creating and setting the instance of appropriate XMLHTTP Request object to a "xmlHttp" variable
function CreateXmlHttp() {
//Creating object of XMLHTTP in IE
try {
//it will work if IE have JavaScript version 5.0
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(oc) {
xmlHttp = null;
}
}
//Creating object of XMLHTTP for non-IE browsers
if(!xmlHttp && typeof XMLHttpRequest != "undefined") {
xmlHttp = new XMLHttpRequest();
}
}
//function to search
function doSearch(searchText) {
//create XMLHttpRequest Object
CreateXmlHttp();
//Requested url
var ajaxRequest = "http://localhost/MyPractice/Result.aspx?search=" + searchText;
//set callback function
xmlHttp.onreadystatechange = callBackMethod;
//Initializes request
xmlHttp.open("GET", ajaxRequest, true);
//send request
xmlHttp.send(null);
}
function callBackMethod() {
//if request completed sucessfully clear the previous result and show the new search results
if(xmlHttp.readyState == 4) {
if(xmlHttp.status == 200) {
clearResults();
showResults();
}
}
}
//function clear previous results
function clearResults() {
var tableBody = document.getElementById("tbSearchResults");
while(tableBody.childNodes.length > 0) {
tableBody.removeChild(tableBody.childNodes[0]);
}
}
//function show search results in a table
//dynamically creating table rows for show the results
function showResults() {
//debugger;
if(xmlHttp.readyState == 4)
{
if(xmlHttp.status == 200)
{
var results = xmlHttp.responseXML;


var customerid = "";
var companyname = "";
var ContactName = "";
var customers = results.getElementsByTagName("Customer");
if(customers.length < 1)
return;
//add header of the search table
addHeader();
//dynamically add search results in a table
for(var i = 0; i < customers.length; i++) {


customerid = results.getElementsByTagName("CustomerID")[i].firstChild.data;
companyname = results.getElementsByTagName("CompanyName")[i].firstChild.data;
ContactName = results.getElementsByTagName("ContactName")[i].firstChild.data;
//creating new table row
addTableRow(customerid, companyname, ContactName);
}
document.getElementById("tblSearchResults").setAttribute("border", "1");
document.getElementById("tblSearchResults").setAttribute("class", "searchtable");
}
}
}
//function for creating new table row
function addTableRow(customerid, companyname, ContactName) {
var row = document.createElement("tr");
var cell = createCellWithText(customerid);
row.appendChild(cell);
cell = createCellWithText(companyname);
row.appendChild(cell);
cell = createCellWithText(ContactName);
row.appendChild(cell);
document.getElementById("tbSearchResults").appendChild(row);
}
//function for create a cell with text
function createCellWithText(text) {
var cell = document.createElement("td");
var textNode = document.createTextNode(text);
cell.appendChild(textNode);
return cell;
}
//add headers of the search result table
function addHeader() {
var row = document.createElement("tr");
var cell = createCellWithText("CustomerID");
row.appendChild(cell);
cell = createCellWithText("CompanyName");
row.appendChild(cell);
cell = createCellWithText("ContactName");
row.appendChild(cell);
document.getElementById("tbSearchResults").appendChild(row);
}

</script>

</head>
<body>
<form id="Form1" method="post" runat="server">
<b>Search For Books</b> <span id="header"></span>
<table width="500" border="0">
<tbody>
<tr>
<td>
Search</td>
<td>
<input type="text" onkeyup="doSearch(this.value);" size="40">
</td>
</tr>
<tr>
<td colspan="2">
<table id="tblSearchResults" width="100%" border="0">
<tbody id="tbSearchResults">
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</form>
</body>
</html>


Result.aspx


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Result.aspx.cs" Inherits="a" %>



Result.aspx.cs



using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class a : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string search = Request["search"];
if (search.Length > 0)
{
Response.Clear();
DataSet dsResults = new DataSet();
//call business layer method for search results
dsResults = getvalue(search);
Response.Clear();
Response.ContentType = "text/xml";
Response.Charset = "utf-8";
string resultsString = dsResults.GetXml();
Response.Write(resultsString);
//end the response
Response.End();
}
else
{
//clears the response written into the buffer and end the response.
Response.Clear();
Response.End();
}
}

else
{
//clears the response written into the buffer and end the response.
Response.Clear();
Response.End();
}

}
private DataSet getvalue(string s)
{

SqlConnection con = new SqlConnection("server=(local);database=northwind;uid=sa;pwd=12345");
SqlDataAdapter da = new SqlDataAdapter("select * from customers where customerid like '%" + s + "%'", con);
DataSet ds = new DataSet();
da.Fill(ds,"Customer");
return ds;

}
}

2 comments:

  1. Hi Santosh...
    Thanks for nice article...
    There is little bit of change in the code....
    In the method showResults() when there are no child of Node,it fires error of null object...
    so i have made little change in the code...
    Its as below...

    if (results.getElementsByTagName("ID")[i].firstChild != null)
    id = results.getElementsByTagName("ID")[i].firstChild.data;
    if (results.getElementsByTagName("CompanyName")[i].firstChild != null)
    companyname = results.getElementsByTagName("CompanyName")[i].firstChild.data;
    if (results.getElementsByTagName("FirstName")[i].firstChild != null)
    ContactName = results.getElementsByTagName("FirstName")[i].firstChild.data;


    Check if the FirstChildNode is exist or not....

    Thanks
    Regards
    Pushkar M Rathod

    ReplyDelete