Click here to Skip to main content
Click here to Skip to main content

Ajax Quick Start FAQ

, 29 Nov 2008
Rate this:
Please Sign up or sign in to vote.
Ajax quick start FAQ

Table of Contents

Introduction

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:

  • Part 1 – Design patterns Factory, Abstract factory, builder, prototype, shallow and deep copy, and singleton and command patterns - SoftArchInter1.aspx  
  • Part 2 – Design patterns Interpreter, Iterator, Mediator, Memento and observer patterns - SoftArch2.aspx 
  • Part 3 – Design patterns State, Strategy, Visitor, Adapter and fly weight pattern - SoftArch3.aspx 
  • Part 4 - Bridge Pattern , composite Pattern ,  Facade Pattern , Chain of Responsibility , Proxy Pattern , Template Pattern - SoftArch4.aspx
  • Part 1 - UML Interview Questions - SoftArch5.aspx 
  • Part 2 - UML Interview Questions - SoftArch6.aspx

You can download by architecture interview question book from here.

(B) What problem does Ajax solve?

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.

(B) What is Ajax?

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.

(B) What is the fundamental behind Ajax?

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.

(B) What is JSON?

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.

(B) How do we use XMLHttpRequest object in JavaScript?

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

(B) How do we do asynchronous processing using Ajax?

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.

(B) What are the various states in XMLHttpRequest and how do we check the same?

(B) How can we get response text?

(B) How can we send request to the server using the XMLHttpRequest component?

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".

(I) How do we pass parameters to the server?

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);

(I) How can we create a class in JavaScript using Atlas?

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.

  1. In this section we register namespace-using register Namespace function. We have named our namespace as Namespace Customer. 
  2. Here we have defined our class clsCustomer.
  3. 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.
  4. Finally we register the class with the namespace.
  5. 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

(A) How do we do inheritance-using Atlas?

(A) How do we define interfaces using Atlas?

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

(A) How do we reference HTML controls using Atlas?

<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

(I) Can you explain Scriptmanager control in Ajax?

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.

(B) Can you explain Enablepartialrendering and UpdatePanel control in Ajax?

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 ‘EnablePartialRendering’ to 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 ‘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:

  • 1 -> Defines the ‘ScriptManager’ control,
  • 2 -> Defines the ‘UpdatePanel’ control,
  • 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 ‘EnableRenderingtrue and with false value to see the effect of how Ajax actually works.

(I) Can you explain the concept of triggers in ‘UpdatePanel’ control?

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:-

  • 1 -> We need to define ‘ControlEventTrigger’ using ‘<atlas:ControlEventTrigger>’ tag.
  • 2 -> In this sample we will link trigger in ‘UpdatePanel1’ with the click event of ‘Button1’.
  • 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’

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

(I) Can you explain the ‘UpdateProgress’ component?

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

(A) How can you do validations in Ajax?

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.

  • 1 -> We have defined a text box ‘TextBox1’ which will be validated for required field.
  • 2 -> We have defined a simple ‘<span>’ HTML tag which will display the error message.
  • 3, 4 and 5 -> We use the XML declarative Ajax script to define that ‘TextBox1’ has validators and it’s a required field validator. To define the required field validator we need the ‘RequiredFieldValidator’ controls inside the validators.
  • 6 -> We then define where the error should be displayed using the ‘ValidationErrorLabel’. In this case we will be displaying error in the span ‘Validator1’ which was defined previously.

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.

(A) How do we do exception handling in Ajax?

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

  • Step 1 -> Right click on the script manager and click ‘Create Error Template’.
  • Step 2 -> Once done click on ‘Edit Templates’.
  • Step 3 -> Enter which error message you want to display when there is a error and then finally click ‘End Template Editing’.

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.

(A) How do we consume web service in Atlas?

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.

  • 1 -> This is the ‘autocompleteextender’ tag which is dragged and dropped from the tool box.
  • 2 -> We need to specify the web service URL and the method of the web service. These can be defined using ‘ServiceMethod’ and ‘ServicePath’ properties.
  • 3 -> We also need to define which text box control the ‘AutoCompleteExtender’ will be point to. This is achieved by using the ‘TargetControlId’ property.

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.

(A) How can we consume data directly in web services?

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.

Other Interview question PDF's

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Shivprasad koirala
Architect http://www.questpond.com
India India

I am a Microsoft MVP for ASP/ASP.NET and currently a CEO of a small
E-learning company in India. We are very much active in making training videos ,
writing books and corporate trainings. Do visit my site for 
.NET, C# , design pattern , WCF , Silverlight
, LINQ , ASP.NET , ADO.NET , Sharepoint , UML , SQL Server  training 
and Interview questions and answers


Comments and Discussions

 
GeneralBeginner should read it Pinmemberspvarapu1-Oct-10 21:03 
thanks so much for such articles by you..
Generalnice for me PinmemberDotNetSharpMan29-Nov-08 8:36 
Generalbeginners PinmemberMichal Stehlik30-Sep-08 3:57 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140721.1 | Last Updated 29 Nov 2008
Article Copyright 2008 by Shivprasad koirala
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid