| Quick Search |
If you are not involved in using the ASP.NET AJAX library offered for ASP.NET, but would like to attribute small amounts of AJAX functionality on your pages, you can do this easily with some javascript and a accessible page.
I only use AJAX in small doses on web sites – mainly to improve the user-experience. Typical instances will engage retrieving a full record based on a user’s selection in a drop down list. I don’t want to perform a full page post back, so I get the JavaScript xmlhttpserver object to do it for me behind the scenes. Here’s an example that fetches the address details for a North wind Traders customer.
First, a generic function to instantiate an instance of xmlhttprequest or xmlhttp, depending on the browser:
function GetXmlHttpObject(handler)
{
var objXmlHttp=null
if (navigator.userAgent.indexOf("MSIE")>=0)
{
var strName="Msxml2.XMLHTTP"
if (navigator.appVersion.indexOf("MSIE 5.5")>=0)
{
strName="Microsoft.XMLHTTP"
}
try
{
objXmlHttp=new ActiveXObject(strName)
objXmlHttp.onreadystatechange=handler
return objXmlHttp
}
catch(e)
{
alert("Error. Scripting for ActiveX might be disabled")
return
}
}
if (navigator.userAgent.indexOf("Mozilla")>=0)
{
objXmlHttp=new XMLHttpRequest()
objXmlHttp.onload=handler
objXmlHttp.onerror=handler
return objXmlHttp
}
}
Now, a simple dropdown list populated by a SqlDataSource control that fetches the CustomerID and Customer Name. Note the empty div, CustomerDetails below the dropdown list:
<div>
<asp:DropDownList
runat="server"
DataSourceID="SqlDataSource1"
DataTextField="CompanyName"
DataValueField="CustomerID">
</asp:DropDownList>
<asp:SqlDataSource
ID="SqlDataSource1"
runat="server"
ConnectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Northwind.mdb"
DataSourceMode="DataReader"
ProviderName="System.Data.OleDb"
SelectCommand="SELECT [CustomerID], [CompanyName] FROM [Customers]">
</asp:SqlDataSource>
</div>
<div></div>
Two more JavaScript functions are needed. One to fire the GetXmlHttpObject method, and denote the page to send a request to, and one to handle the response by checking the read State property of the object for a value of 4 or complete, then to write the response to the empty div:
function GetCustomer(id)
{
var url="FetchCustomer.aspx?CustomerID=" + id ;
xmlHttp=GetXmlHttpObject(stateChanged);
xmlHttp.open("GET", url , true);
xmlHttp.send(null);
}
function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
document.getElementById('CustomerDetails').innerHTML=xmlHttp.responseText;
}
}
So now we have a page that gets called by xmlhttp (FetchCustomer.aspx) and we have a value to pass to the query string for the page. So the next thing to do is to add an event handler to the Dropdown List that will fire the GetCustomer() event and pass a CustomerID value:
if (!Page.IsPostBack)
{
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, "");
}
DropDownList1.Attributes["onChange"] = "GetCustomer(this.value);";
HttpResponse myHttpResponse = Response;
HtmlTextWriter myHtmlTextWriter = new HtmlTextWriter(myHttpResponse.Output);
DropDownList1.Attributes.AddAttributes(myHtmlTextWriter);
And finally, the code for the FetchCustomer.aspx page. Everything has been removed from the .aspx file except the first line. We don’t want DocTypes or default <form> tags disturbing the piece of html to be emitted in the response:
<%@ Page AutoEventWireup="true"
CodeFile="FetchCustomer.aspx.cs" Inherits="FetchCustomer" %>
And the code-behind makes doubly sure by calling Response.Clear() before querying the database and emitting the resulting data as html:
using System;
using System.Data;
using System.Data.OleDb;
using System.Text;
public partial class FetchCustomer : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Clear();
StringBuilder sb = new StringBuilder();
sb.Append("<br />");
string provider = "Provider=Microsoft.Jet.OLEDB.4.0;";
string db = "Data Source=|DataDirectory|Northwind.mdb";
string connstr = provider + db;
string query = "SELECT * FROM Customers WHERE CustomerID = ?";
OleDbConnection conn = new OleDbConnection(connstr);
OleDbCommand cmd = new OleDbCommand(query, conn);
cmd.Parameters.AddWithValue("", Request.QueryString["CustomerID"]);
conn.Open();
OleDbDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
sb.Append(dr[1].ToString() + "<br />");
sb.Append(dr[4].ToString() + "<br />");
sb.Append(dr[5].ToString() + "<br />");
sb.Append(dr[6].ToString() + "<br />");
sb.Append(dr[7].ToString() + "<br />");
sb.Append(dr[8].ToString() + "<br />");
sb.Append("Tel: " + dr[9].ToString() + "<br />");
}
dr.Close();
dr.Dispose();
conn.Close();
conn.Dispose();
Response.Write(sb.ToString())
Response.End();
}
}
Posted in AJAX
You can follow any responses to this entry through the RSS 2.0 Feed. You can leave a response , or trackback from your own site.
Hey…..nice post!!
Awesome, No more words to explain
just….cool blog.
Yours is a wonderful easy to use script. Thank you for sharing this.
Hi webmaster – This is by far the best looking site I’ve seen. It was completely easy to navigate and it was easy to look for the information I needed. Fantastic layout and great content! Every site should have that. Awesome job
Sorry for the huge review, but I’m really loving the new Zune, and hope this, as well as the excellent reviews some other people have written, will help you decide if it’s the right choice for you.
Great stuff from you, man. Ive read your stuff before and youre just too awesome. I love what youve got here, love what youre saying and the way you say it. You make it entertaining and you still manage to keep it smart. I cant wait to read more from you. This is really a great blog.
This post was very nicely written, and it also contains a lot of useful facts. I appreciated your professional way of writing this post. Thanks, you have made it very easy for me to understand.
Hrmm that was weird, my comment got eaten. Anyway I wanted to say that it’s nice to know that someone else also mentioned this as I had trouble finding the same info elsewhere. This was the first place that told me the answer. Thanks.
Resources like the one you mentioned here will be very useful to me! I will post a link to this page on my blog. I am sure my visitors will find that very useful.
I gone through your content and I must say you wrote it with pride. I’m bookmarking your page now.
You will find spam reviews in your blog.
Sorry for the huge review, but I’m really loving the new Zune, and hope this, as well as the excellent reviews some other people have written, will help you decide if it’s the right choice for you.
Your web blog is undoubtedly displaying complications on my Internet internet browser.
Bless you! My crew suggested a web parser in your web publication so our staff members will aggreate your great text, with good attribution however, yet somehow there seems to be an error. The blog seriously is not granting us to. Can certainly you allow us?
I am quite frankly right here to aid, you’ll need to moderate comments here. Yes really !.
Bless you! We are considering for upcoming essayissts, may you be attracted? Now this is not going to help you prosperous sadly i must say there is an eye-catching pay and if you particularly love publishing then this in turn opportunity is for you.
principle? Is undoubtedly that deep under creative commons?