Microsoft Ajax, from the bottom up.
Recently i started using Microsoft Ajax and found it very exiting, I also decided to find out once and for all what is all the fuss about JSON.
So In these series of posts, i will try to explain Microsoft ajax and what is so great about it.I will start by introducing the old way we did ajax first, Improve my sample with JSON and then go over ms ajax.
In the traditional web application, the interaction between the user and the server is something like this:
The user opens some url and access a web application
Some page events occur and the page is first renders from the server.
The user then clicks some links or buttons (which need to get some data that is stored some where in the server, probably a DB server)
The user waits while the server get what ever he was told to do and re-renders the entire page.
The user is waiting for this re-rendering every time this postback happens.
So what if we could let the user continue his work, or at least release him from the tedious and slow re-rendering. This is where ajax comes in.
So what is ajax: ajax stands for Asynchronous JavaScript and XML, lets try to explain in a simpler words:
Ajax is basically a way for writing better web applications.
And when i say better web applications i mean applications that are less slow and less tedious.
Ajax is our way for going back to the server without the user knowing it, and without the page doing a submit ,But actually going "silently" to the server and bringing the data. After this data was brought to the page we can simply change the UI of our page in the client side (e.g JavaScript)
And what we gain from building an ajax driven web application is a less slow and tedious application that needs less time and the page in a very quicker way shows us what ever he we told it to do
For instance try the google map web site and check out how cool is it to click some buttons or scroll some scorlles in the page without having to see the entire page renders itself all over again each time we press some button.
So lets start up by building a simple web page that does ajax the old fashion way:
Out sample will ask the user to select a user name from a select box, and according to his name we will show into the label some details about this person.
In the old days without ajax we set the AutoPostBack of the DropDownList to true, and in the event handler of the selected index change event we checked this user criteria and set the label on the server side.
This is obviously a burden for a user waiting for this post back to end.
Lets show the "old" ajax way, To do so we will do the following:
1. Open vs.net 2005/2008 and create a new web site/web application containing a single web page : SimpleAjaxSample.aspx .Our solution will something like this:
2. Add the following code to the aspx file to create a simple drop down list and to handle its onchange event:
<body>
<form id="form1" runat="server">
<div dir="rtl">
<asp:DropDownList runat="server" ID="ddlEmployees" onchange="CheckIfTeacher();">
<asp:ListItem Text="pini" Value="pini"></asp:ListItem>
<asp:ListItem Text="zohar" Value="zohar"></asp:ListItem>
<asp:ListItem Text="eran" Value="eran"></asp:ListItem>
</asp:DropDownList>
<br />
<asp:Label runat="server" ID="lblDetails" ></asp:Label><br />
</div>
</form>
</body>
3. Add the following code to the aspx file in the head section to handle the onchange event using BLOCKED SCRIPT
<script>
var oXmlhttp;
function CheckIfTeacher()
{
//Get the selected name
var ddlObj = document.getElementById("<%= ddlEmployees.ClientID %>");
var indexSelected = ddlObj.selectedIndex;
var sName = ddlObj.options[indexSelected].value;
//Get details for the given user
oXmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
var sURL = "http://localhost/AjaxTest/GetTeacherDetails.aspx?sName=" + sName;
oXmlhttp.open("GET", sURL, true);
oXmlhttp.onreadystatechange = GotAnswer;
oXmlhttp.send(null);
}
function GotAnswer()
{
// if xmlhttp shows "loaded"
if (oXmlhttp.readyState == 4)
{
//if "OK"
if (oXmlhttp.status == 200)
{
var result = oXmlhttp.responseText;
//Parse this xml
var lblObj = document.getElementById("<%=lblDetails.ClientID %>");
var oXML = new ActiveXObject("Microsoft.XMLDOM");
oXML.async = false;
oXML.loadXML(result);
var sName = oXML.selectSingleNode("//UserData/Name").text;
var sAge = oXML.selectSingleNode("//UserData/Age").text;
var sHobbies = oXML.selectSingleNode("//UserData/Hobbies").text;
lblObj.innerHTML = "Name:" + sName + " Age=" + sAge + " Hobbies:" + sHobbies;
}
else
{
alert("Problem retrieving XML data");
}
}
}
</script>
Notes:
The method CheckIfTeacher gets the name from the select box
creates a new Microsoft.XMLHTTP object to handle the web request we are about to perform.
Setting the url to an aspx page and add a querystring paramater to send to it.(This page will be explained soon)
define the onreadystatechange property for the Microsoft.XMLHTTP object.This property will define the callback function that will be activated when the web request has finished.In our sample it is the GotAnswer function
The GotAnswer will check if the web request succeeded and if so load the xml result to a client side parser(using Microsoft.XMLDOM).
Then parse the result and place it in some label.
Note that a better solution that will be cross browsing solution is to check in which browser we are at, such as:
// code for Mozilla, etc.
if (window.XMLHttpRequest)
{
oXmlhttp = new XMLHttpRequest()
}
//code for IE
else if(window.ActiveXObject)
{
oXmlhttp = new ActiveXObject("Microsoft.XMLHTTP")
}
This page will have no content (so delete everything but the page directive). and his CS will like like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class GetTeacherDetails : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request["sName"] == null)
{
Response.Write("");
}
else
{
Response.Write(GetDetails(Request["sName"].ToString()) .ToString());
}
}
private string GetDetails(string sName)
{
string sDetails = "<UserData><Name>{0}</Name><Age>{1}
</Age><Hobbies>{2}</Hobbies></UserData>";
switch (sName)
{
case "pini":
return string.Format(sDetails,"pini","30","Soccer,Dancing");
break;
case "zohar":
return string.Format(sDetails, "zohar", "25", "Ballete,Tennis");
break;
case "eran":
return string.Format(sDetails, "eran", "15", "Programming,Dancing");
break;
default:
return string.Empty;
}
}
}
Well, This is about it.What we got is a page looks like this:
and when the user pick some option from the select box:
with no flickers or some heavy waiting.
On the next post we will show how to improve our sample using JSON.