![]() |
Web Development »
ASP.NET »
General
Beginner
License: The Code Project Open License (CPOL)
Ajax Quick Start FAQBy Shivprasad koiralaAjax quick start FAQ |
Javascript.NET1.0, .NET1.1, .NET2.0, .NET3.0, .NET3.5, ASP.NET, Ajax, Architect
|
||||||||||
|
Advanced Search Add to IE Search |
|
|
|
||||||||||||||||
This FAQ is like a starter kit. It will help you understand the main aspects of Ajax in a rapid fashion.... So get set go....
Lately i have been writing and recording videos heavily on design patterns , UML and many architectural stuff you can visit this link for design pattern and UML videos.
You can read my previous articles on design patterns and UML in the below links:
You can download by architecture interview question book from here.
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:
Figure 18.1:- The problem
Figure 18.2:- Synchronous 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.
JSON is a very lightweight data format based on a subset of the JavaScript syntax, namely array and object literals. JSON allows communicating with server in a standard way. JSON is used as communication notation instead of XML.
var oBike =
{
"color" : "Green",
"Speed”: 200,
};
alert(oBike.color); //outputs "Green"
alert(oBike.Speed); //outputs 200
The above code creates an javascript object bike with two properties Color and Speed.
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?
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.If you want to check the state use
if (xmlHttpObj.readyState ==4).
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 +
"/XmlHttpExample1/WebForm1.aspx?value=123", true);
xmlHttpObj.open("POST","http://" + location.host +
"/XmlHttpExample1/WebForm1.aspx?value=123", true);
JavaScript is object based language and this a new feature which is provided by Atlas. Using Atlas you can now define classes, do inheritance, create interfaces etc in JavaScript. You can now implement all the object-oriented concepts in JavaScript. So let us understand the same with an example.
Once you install the Atlas setup you will get the following JS files and a web.config file as shown in the below figure. In order to use Atlas you need to add the JS files in your project. You can see from the figure below we have added the JavaScript files and the web.config file to the project that was installed with Atlas setup. We also need to add Microsoft.Web.Atlas.dll to the project.Components.js has the class definition, which we will discuss in the coming sections.
Figure 18.4:- Ajax folder structure
Below figure has two important code snippets the top one is taken from components’ it defines the class definition and the second code snippet is of ASPX page which consumes the JavaScript class. So let us understand all the numbered points one by one.
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.
Function.abstractMethod () defines a method as abstract. 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" />
You can reference the above HTML defined button using the below code snippet of JavaScript. We have also attached the on click method with the button. This method will be called when we click the button.
var btnVisibility = new Sys.UI.Button($('Button1'));
btnVisibility.intialize();
btnVisibility.click.add(onClick);
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:-
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:
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 ‘EnablePartialRendering’ to true. If this is false then the full page will refresh. 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. Below figure ‘ScriptManager and UpdatePanel' shows how the ‘ScriptManager’, ‘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 ‘ScriptManager and UpdatePanel code view’.
Note: - ‘ScriptManager’ should come as a first control on any Ajax ASPX page.
So:
ScriptManager’ control, UpdatePanel’ control, ContentTemplate’ tag and 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 ‘EnableRendering’ 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’. ‘ControlEventTrigger’ are defined using ‘<atlas:ControlEventTrigger>’ tag. We have numbered the code snippet below so let’s understand the same with numbers:-
ControlEventTrigger’ using ‘<atlas:ControlEventTrigger>’ tag.UpdatePanel1’ with the click event of ‘Button1’.<atlas:ControlEventTrigger>’ tag we need to define the control and event using ‘ControlId’ and ‘EventName’ properties respectively.UpdatePanel1’ is refreshed.Figure 18.12: - Code snippet for ‘ControlEventTrigger’
Using ‘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
We can perform all the necessary validation like required field, type checking, range checking etc using Ajax. Below is a small snippet which shows how to use a required field validator. We have numbered the code snippet to understand the code more proper.
Figure 18.15:- Validations in Ajax
Note :- The above sample shows a sample for 'requiredFieldValidator' , but we can also use other validators like rangeValidator, typeValidator, rangeValidator and regexValidator. As this is a interview book we will not be getting in to details of the other validators, please feel free to practice some sample for the same.
Exception handling in Ajax is done using the ‘ErrorTemplate’ which forms the child tag of ‘ScriptManager’. There are three steps to achieve error handling in Ajax. Below figure ‘ErrorHandling’ in Ajax shows the three steps in a pictorial fashion.
Figure 18.16:- Error Handling in Ajax
Just click back on the HTML view to see what we have in the HTML. You can see the ‘ErrorTemplate’ tag is the fundamental driver for handling errors.
There are two ways by which we can consume a web service one is using ‘Services’ tag and the other is by using properties defined in Ajax components like ‘ServicePath’ , ‘ServiceMethod’ and ‘ServiceURL’.
We can define the web service URL in the ‘Services’ tag using ‘atlas:ServiceReference’ tag. ‘Path’ property defines the web service URL. If we also want to generate javascript proxy we need to set the ‘GenerateProxy’ to true. We have also set one more property i.e. ‘InlineProxy’ property needs to be true so that the proxy code is available to the client javascript.
Figure 18.17 :- Referencing web service
If you make ‘InLineProxy’ property to true you should see the below code snippet when do a view source on the browser.
<script type="text/javascript">
var WebService=new function()
{
this.appPath = "http://localhost:4430/AtlasWebSite3/";
var cm=Sys.Net.ServiceMethod.createProxyMethod;
cm(this,"HelloWorld");
cm(this,"GetWordList");
}
Let’s look at the second method using ‘ServiceMethod’ and ‘ServicePath’. Atlas components which display data to the end user have certain properties which help you in consuming web service and invoke methods on those web services. So let’s demonstrate a simple sample using the ‘AutoCompleteExtender’ component. ‘AutoCompleteExtender’ is used to enhance a text box with auto complete functionalities. Below is a text box which is enhanced with the ‘AutoComplete’ feature.
Figure 18.18: - Textbox with AutoComplete feature
So let’s first define the web service. Below is a simple web service which exposes a word list for implementing the auto complete feature in the text box.
Figure 18.19: - Web Service for auto complete functionality
Once we have defined the web service we need to drag and drop the ‘AutoCompleteExtender’ on the ASPX page.
Figure 18.20: - Drag and drop AutoCompleteExtender
Now if you do a view source you should see the below code in HTML. We have numbered the code to highlight the important section.
That’s it, run the program and see text box performing the auto extender functionality.
Figure 18.21: - ServiceMethod and ServicePath
The ‘ServiceURL’ property can be found in DataSource control.
We can consume data directly using ‘Sys.Data’ controls. We know this is a very short answer for such an important question, but the bandwidth of this book does not allow for the same. We suggest the readers to practice some sample using the ‘Sys.Data’ control.
Note: - We have left important controls like Data controls, Login controls, Web part controls, mobile controls and profilescriptservice control. These controls will be rarely asked during interviews, but from project aspects they are very important.
| You must Sign In to use this message board. | |||||||||||||||
|
|||||||||||||||
|
|||||||||||||||
|
|||||||||||||||
|
|||||||||||||||
General
News
Question
Answer
Joke
Rant
Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads.
|
PermaLink |
Privacy |
Terms of Use
Last Updated: 29 Nov 2008 Editor: Deeksha Shenoy |
Copyright 2008 by Shivprasad koirala Everything else Copyright © CodeProject, 1999-2010 Web21 | Advertise on the Code Project |