Introduction - What is AJAX?
Why use AJAX?
There are a couple of reasons to use AJAX in lieu of the traditional form submission. The first is that it is very light weight: instead of sending all of the form information to the server and getting all of the rendered HTML back, simply send the data the server needs to process and get back only what the client needs to process. Light weight means fast. The second reason to use AJAX is because (as the logo in the link above makes clear) AJAX is cool.
Using AJAX with ASP.NET
Using the code
There are four parts of the code that are important to look at:
- The HTML
There are two form elements that will interact with AJAX. The input button "
btn1" will invoke the AJAX code, which will make a server call and fill the select element "
<input id="btn1" value="Fill Select" type="button" <BR> onclick="getOptions();">
getOptions() will do the main work.
var request = new Request();
var url = "http://localhost/ajax/";
request.GetNoCache(url + "requests/getOptions.aspx",
if (result.status==HttpStatus.OK && result.responseText != "")
var vals = result.responseText.split("~");
for (i=0; i<vals.length; i++)
var pair = vals[i].split("|");
var op = new Option(pair, pair, false, false);
var sel = document.getElementById("select1");
sel.options[sel.length] = op;
alert("Remember that the new values in form" +
" element 'select1' are not in viewstate." +
" Code appropriately.");
alert('Get options failed.');
- The ASPX file.
The important thing here is that the aspx file only returns the string (XML) data from the code behind.
<%@ Page language="c#"
- The code behind.
protected string result = string.Empty;
private void Page_Load(object sender, System.EventArgs e)
for (int i=0; i<10; i++)
result += i.ToString() + "|option " + i.ToString() + "~";
result = result.Substring(0, result.Length - 1); <BR>}
As you can see, it is very easy to have a lightweight AJAX component interact with ASP.NET. I know what you are thinking: "Steve, wait a minute: I thought you had to use XML to use AJAX?" From the example, you can see that the string being returned is a pipe and tilde delimited string. You do not have to use XML. There are a lot of places where XML would be very useful, but using this implementation it is not required.