In order to answer this question first lets understand how does browser and server work when we request any website. Below figure depicts pictorially the web environment. When client sends data to the server it post backs form element data, hidden fields,images,cookie information to the server and server make the page and sends the same information back to the browser. The bad part this happens with every request and response.
Below are the issues with the above model:
- Unnecessary data transfers: - In the above model, unnecessary data is transferred between client and server. For instance, the whole page is posted and refreshed even when we want small data of the page to be refreshed.
Figure 18.1:- The problem
- Synchronous processing: - When a user requests for a page he has to wait until the complete round trip happens. In short, the request / response work on a synchronous model rather than asynchronous which makes user experience very difficult. How many times it has happened that you are requesting a page and you see the below screen…frustrating right.
Figure 18.2:- Synchronous processing
- Unnecessary processing by server: - Because we are posting unnecessary information to the server, the server is overloaded with unnecessary processing.
Ajax is a set of client side technologies that provides asynchronous communication between user interfaces and web server. So the advantages of using Ajax are asynchronous communication, minimal data transfer and server is not overloaded with unnecessary load.
XmlHttpRequest is the fundamental behind Ajax. This allows the browser to communicate to a back end server asynchronously.XmlHttpRequest object allows the browser to communicate with server with out posting the whole page and only sending the necessary data asynchronously.
var oBike =
"color" : "Green",
alert(oBike.color); //outputs "Green"
alert(oBike.Speed); //outputs 200
Below is a code snippet, which shows how to use
XMLHttpRequest object. In this code snippet, we are sending a GET request on the local IIS. Below is the explanation of the code snippet according to the numbers specified in the code snippet?
- 1,2,3,4 -> This is like checking which is this browser and create the objects accordingly. XMLHttpRequest objects have different ways of technical implementation according to different browsers. In Internet explorer it is an activex object but in other browsers its XMLHttpRequest. So if windows.XMLHttpRequest does not return null then we can create XMLHttpRequest object. If it returns null then we can try creating the activex object Microsoft.XMLHttp object. In case it fails probably then probably we have an older version of XML that is MSXML2. So in the error handling we will try to create the MSXML2 object.
- 5 -> In this snippet, we OPEN the connection to the local host server and specify what type of request we are using. In this case, we are using the GET method.
- 6 -> Finally, we make a request to the server.
- 7 -> Here we get the request sent by the server back to the client browser. This is a blocking call as we need to wait to get the request back from the server. This call is synchronous that means we need to wait for the response from the server.
Figure 18.3:- Basic XMLHTTP code
xmlHttpObj.onreadystatechange = function1();
Above is the code snippet, which will help us to do asynchronous processing. So
function1 () will be called when the
XMLHTTP request object goes to on ready state change.
Note :- All the above answers are discussed in detail in the below section.
Abort ():- This method cancels a user request.
getAllResponseHeaders ():- Returns a collection of HTTP headers as string. If you want a specific header value, you can use
getResponseHeader (“header name”)
Open (“method”, “URL”, “async”, “uname”, “pswd”):- This method takes a URL and other values needed for a request. You can also specify how the request is sent by GET, POST, or PUT. One of the important values is how this request will be sent asynchronously or synchronously. True means that processing is carried after the
send () method, without waiting for a response. False means that processing is waits for a response before continuing.
Send (content):- Sends a request to the server resource.
SetRequestHeader (“label”,” value”):- Sets label value pair for a HTTP header.
Onreadystatechange: - This is a event handler, which fires at every state change.
- Ready State: - Returns the current state of the object.
- 0 = uninitialized
- 1 = loading
- 2 = loaded
- 3 = interactive
- 4 = complete
If you want to check the state use
if (xmlHttpObj.readyState ==4).
- Response Text: - Returns the response in plain string.
- Response: - Returns the response as XML. Therefore, this gives us DOM object model, which can then be traversed.
- Status: - Returns the status as a numeric For instance 404 for "Not Found" or 200 for "OK", 500 for "Server Error" etc.
- Status Text: - Returns the status as a string. For instance, "not found" or "OK".
Below are the two ways of passing data to server. The first one shows by using GET and the second by POST.
xmlHttpObj.open("GET","http://" + location.host +
xmlHttpObj.open("POST","http://" + location.host +
Figure 18.4:- Ajax folder structure
- In this section we register namespace-using register Namespace function. We have named our namespace as Namespace Customer.
- Here we have defined our class clsCustomer.
- We have defined two properties Customer Code and Customer Name. Both the properties have get and set function. We have also defined a read-only function getCodeAndName, which returns the concatenation of customer code and customer name.
- Finally we register the class with the namespace.
- In this section we have consumed the class.getCOdeAndName will display the concatenated value of customer code and customer name.
Note: - You can find the above code in AtlasClass folder. Feel free to experiment with the same.
Figure 18.5:- Code snippet for consuming the class
Below is a numbered code snippet, which will answer both the upper questions. Let us understand in detail the numbered sections.
- 1 and 2 -- This defines the interface definition.
Function.abstractMethod () defines a method as abstract.
- 3 - We need to register the interface, which is done by using register Interface method.
- 4, 5 and 6 - Inheritance and Interface is defined when we register the class. Register Class has three inputs. 4th section defines the main class, which needs to be registered. 5th section defines the parent class from which it will inherit. 6th section defines the interface. So
clsMyCustomCustomer is the class which derives from
clsCustomer and implements I Customer interface.
Figure 18.6:- Inheritance and Interfaces in action
<input id="Button1" type="button" value="button" />
var btnVisibility = new Sys.UI.Button($('Button1'));
You can refer other HTML elements like Label, Textbox m Checkbox, Hyperlinks etc using the Sys.UI.
Note: - We have added some extra questions in this edition for Ajax as promised. In CD we have provided ‘AtlasSetup’. This you need to install to get the below Ajax project template in VS.NET 2005.
Figure 18.7 :- Ajax template
One more thing to ensure before we start Ajax is to add the Ajax controls on the tool box. So do the following right click on the tool box ? click choose items ? click ‘Browse’ button ? add ‘C:\Program Files\Microsoft ASP.NET\Atlas\v2.0.50727\Atlas\Microsoft.Web.Atlas.dll’. Once done you should see some new components as shown in figure ‘Ajax controls’. Now we are ready to see how Ajax works.
Figure 18.8:-Ajax control
Scriptmanager control is the central heart of Ajax. They manage all the Ajax related objects on the page. Some of the core objectives of scriptmanager control are as follows:-
- Helps load core Ajax related script and library.
- Provides access to web services.
- ASP.NET authentication, role and profile services are loaded by scriptmanager control.
- Provided registration of server controls and behaviors.
- Enable full or partial rendering of a web page.
- Provide localization features.
In short , any Ajax enable page should have this control.
Let’s answer the above questions with a simple sample Ajax application. As we move through this application we will be answering the above questions. If you have already installed the Ajax setup and added the reference to ‘Microsoft.Web.Atlas.dll’ you should see those controls in your tool box as shown in the above figure ‘Ajax controls’. Let’s follow the below steps to complete this sample:
- So first drag and drop ‘
ScriptManager’ control from the tool box on the ASPX page. We have already discussed in the previous question how important a ‘
ScriptManager’ control. In order to ensure that the full page does not post back we need to make ‘
true. If this is false then the full page will refresh.
- Now drag the ‘
UpdatePanel’ control from the tool box on the ASPX page. Using ‘
UpdatePanel’ we can restrict the area of post back. In normal ASPX pages the whole page posts back i.e. there is a full refresh. But by using ‘
UpdatePanel’ we define which area has to be refreshed. ‘
UpdatePanel’ forms a container for controls and thus defining the area of post back.
- Now we drag two controls a button and textbox and put a long loop code as shown in figure ‘Long loop code’.
Below figure ‘
UpdatePanel' shows how the ‘
UpdatePanel’ and ‘
EnablePartialRendering’ will look like.
Figure 18.9 : - ScriptManager and UpdatePanel
Figure 18.10: - Long loop code
Just to understand the inside basics you can switch in to the HTML of the ASPX you should see the below code snippet as shown in figure ‘
UpdatePanel code view’.
Note: - ‘ScriptManager’ should come as a first control on any Ajax ASPX page.
- 1 -> Defines the ‘
- 2 -> Defines the ‘
- 3 -> all the controls should come under ‘
ContentTemplate’ tag and
- 4 -> defines the controls which will be wrapped under the ‘
UpdatePanel’ tag. Figure ‘Long loop code’ is called on button1 click to do some heavy task so that we can judge the advantage of using Ajax.
Figure 18.11: - Script Manager and Update Panel code view
Once done you can check the project with ‘
true and with
false value to see the effect of how Ajax actually works.
Triggers are child tags for ‘
UpdatePanel’ tag. Many times we would like to update the panel when some event occurs or a value change on a control. This can be achieved by using triggers. There are two types of triggers ‘
ControlEventTrigger’ and ‘
ControlValueTrigger’. So let’s first understand ‘
ControlEventTrigger’. Using ‘
ControlEventTrigger’ we define on which control and at which event the update panel should refresh. Below is a simple code snippet for ‘
ControlEventTrigger’ are defined using ‘
<atlas:ControlEventTrigger>’ tag. We have numbered the code snippet below so let’s understand the same with numbers:-
- 1 -> We need to define ‘
ControlEventTrigger’ using ‘
- 2 -> In this sample we will link trigger in ‘
UpdatePanel1’ with the click event of ‘
- 3 -> In the ‘
<atlas:ControlEventTrigger>’ tag we need to define the control and event using ‘
ControlId’ and ‘
EventName’ properties respectively.
So now when the button click event happens ‘
UpdatePanel1’ is refreshed.
Figure 18.12: - Code snippet for ‘ControlEventTrigger’
ControlValueTrigger’ we can update a panel when an external control has reached some value. So again we need to define the same in a ‘
Triggers’ tag. We need to put the ‘
ControlvalueTrigger’ tag with control and property defined using the ‘
ControlId’ property. So according to below code snippet when the value of ‘
Textbox1’ changes we need to update the top panel.
Figure 18.13:- ‘ControlValueTrigger’ code snippet
Some times we have huge task at the back end for processing and we would like to show a user friendly message until the processing finishes. That’s where the ‘UpdateProgress’ control comes in to picture.
To use ‘UpdateProgress’ control we need to use ‘UpdatePanel’ tag. ‘UpdateProgress’ forms the child tag of ‘UpdatePanel’ control. Until the server processing finishes we can display a message which can be defined in the ‘ProgressTemplate’ tag which is the child tag of ‘UpdateProgress’ tag.
Figure 18.14:- Update Progress in action