AJAX Client-Side Life Cycle Events

The Microsoft AJAX Library also includes a client-based event life cycle. You can use this life cycle to intercept events when the page runs, and load your code as required. Think of this as similar to how you work with code-behind files. For example, in a code-behind file you might write code in the Page_Load event. Similarly, in the code you write to run in the browser, you can implement the Sys.Application.load event.
Fortunately, the life cycle of your client code is very similar to that of your server code. This includes events for init, load, unload, and disposing. In this way, the Application client object works in a similar way as the Page object in your server code. To take advantage of this event model you must, of course, use a ScriptManager control on your page. You register an event in script by using the add_event syntax. The following code shows how you would register code with the Sys.Application.Load event.

Sys.Application.add_load(PageLoad);
function PageLoad(sender)
{   
//page-load code goes here
}

The library also allows you to unregister (or remove) events. You do so in a similar manner, by using the remove_ syntax. The following shows an example.

Sys.Application.remove_load(PageLoad);

You can follow this similar model to trap other events in the library. For example, another important class with events that you might want to work with is the PageRequestManager class of the Sys.WebForms namespace. This class is used for partial-page updates and asynchronous postbacks. It includes the following events:
■initializeRequest:- Raised before the asynchronous postback starts ■beginRequest:- Raised as the asynchronous postback is sent to the server
■pageLoading:- Raised when the asynchronous postback response first comes back from the server
■pageLoaded:- Raised after the content has been loaded from the results of the asynchronous postback
■endRequest:- Raised when the asynchronous postback has been completed.

As you might have guessed, the UpdatePanel control relies heavily on these events. You can also use these events to cancel asynchronous postbacks, provide custom information or animation to the user when these events are fired, or simply run your code at specific times within the request.

Programming is Easy. …

Advertisements

What is ASP.NET AJAX ?

ASP.NET includes many components that help to enable AJAX features for developers. These components have a common goal:-

To improve the user’s experience by providing developers with the ability to create more responsive web applications.

The following are the ASP.NET components related to AJAX capabilities:
1)Microsoft AjAX Library :- The Microsoft AJAX Library is a set of JavaScript files that make programming client-side JavaScript easier.
2)ASP.NET AjAX server controls :-ASP.NET ships with a set of AJAX server controls that can be embedded in your webpages to enable partial-page updates, communicate with a server process to indicate progress, and periodically update portions of a page.
3)jQuery:- jQuery is a code library that makes it easier to write client-side scripts and AJAX applications. It is actually an open source library (see http://jquery.com/). ASP.NET includes the scripts for jQuery and jQuery IntelliSense support within the Visual Studio IDE. 
4)AjAX Control Toolkit :-The AJAX Control Toolkit is a set of community-created and supported controls that show off the power of AJAX. You can use these controls in your webpages to enable many client-side features typically found only in applications running on the desktop, controls such as masked edit boxes, slider controls, filtered text boxes, modal pop-up windows, and much more.
5)Client-side web service support :-ASP.NET and AJAX provide support for calling web services asynchronously from the client by using JavaScript Object Notation (JSON) serialization and XML.
6)ASP.NET standard controls:- The controls that ship with ASP.NET also make use of JavaScript on the client. It is easy to forget about this because you are not required to write any JavaScript to get this interactivity. Examples of ASP.NET controls that use JavaScript include the validation controls, the Web Part controls, the menu control, the TreeView control, and the Calendar control.

Uses and Benefits of ASP.NET AJAX :-
1)Partial-page updates :- This feature allows you to define an area of a webpage to post back and update independently from the rest of the page. Only the updated content will be refreshed when the request completes. This ensures that the user stays within his or her current context. It also gives users the feeling that they are interacting with the application (and not a server).

2)Client-side processing :-This interactivity provides immediate feedback and responsiveness to users. With client script, you can enable functionality such as collapsible areas of a page, tabs on a webpage, data sorting on the client, and much more.

3)Desktop-like Ui :- With AJAX, you can provide users with controls such as modal dialog boxes, progress indicators, masked edit boxes, tooltips, and more. This helps make the user experience between web and rich desktop applications much more similar.

4) Progress indication :- This allows you to track the progress of a server-side process and continuously update the user. This gives users the feeling that they are in control and assures them that the application is still processing (as with a desktop application).

5) improved performance and higher scale :- You can achieve increased performance and scale by processing portions of a page on just the client. You then take advantage of the user’s machine, which takes the load off the server. This results in real and perceived performance and scalability increases.

6)Web service calls from the client:- This allows you to call back to the server directly from client script running in a browser and then show the results to the user (often by using partial-page updates).

7)Cross-browser, cross-platform support :- JavaScript, AJAX, and jQuery are all supported on multiple browsers and multiple platforms. This allows you to write interactive applications that run in more client environments than the average desktop application.

The AJAX Server Controls:-
The ScriptManager Controls:-
Each page you write that uses ASP.NET AJAX requires one (and only one) instance of a ScriptManager control. The ScriptManager control is responsible for pushing the Microsoft AJAX Library down to the client when your page is requested.
It also manages partial-page updates, progress indicators, and more. You add the ScriptManager control to your page source. It does not have a visual representation. It is simply a control used to manage AJAX processing.
The basic page markup for a ScriptManager control in Source view looks as follows.

<asp:ScriptManager ID="ScriptManager1" runat="server"> 
</asp:ScriptManager>

By default, the ScriptManager control’s EnablePartialRending property is set to true. This indicates that the page supports partial-page updates. You can use this property to turn this feature off if needed.

The ScriptManagerProxy Controls:-
You will often need to support AJAX in a user control you write or directly in the master page of a site. This presents an issue, because a page can contain only a single ScriptManager control. Having one inside your user control and another inside the page that consumes the user control, for example, would be a problem. To overcome this issue, you can use the ScriptManagerProxy control.
The ScriptManagerProxy control can be used either by child pages that use a master page that already defines a ScriptManager control or by user and custom controls that you write. You use it much the same way you would a ScriptManager control. You can register scripts that are specific to the child page or control that you are writing. ASP.NET takes care of the rest.

The UpdatePanel Control :-
The UpdatePanel control allows you to define areas of a page that should post back to the server independent of the rest of the page. The UpdatePanel control is a container for other controls. The controls you put inside the UpdatePanel control that cause a postback to the server will be managed as partial-page updates.


 
<asp:UpdatePanel ID="UpdatePanel1" runat="server">   
<Triggers>     
<asp:AsyncPostBackTrigger ControlID="ButtonSearch" EventName="Click" />   
</Triggers>   
<ContentTemplate>     
        ... Grid View markup ...    
</ContentTemplate>
 </asp:UpdatePanel>

The UpdateProgress Control:-
The UpdateProgress control is used to provide information in the form of graphics or text that is displayed to the user during a partial-page update.

<asp:UpdatePanel ID="UpdatePanel1" runat="server">   <ContentTemplate>            
 <asp:GridView ID="GridView1" runat="server">     </asp:GridView>     <asp:UpdateProgress ID="UpdateProgress1" runat="server">       <ProgressTemplate>        
 <div style="font-size: large">Processing ...</div>       </ProgressTemplate>     
</asp:UpdateProgress>   
</ContentTemplate> 
</asp:UpdatePanel>

The Timer Control:-
The ASP.NET Timer control is an AJAX control that can be used to update portions of a page on a periodic, timed basis. This is useful if you need to update an image such as an advertisement on a webpage or perhaps a value such as a stock ticker or a news ticker. The Timer control can also be used to simply run code on the server on a periodic basis.

<asp:UpdatePanel ID="UpdatePanel1" runat="server">   <ContentTemplate>    
 <asp:Image ID="Image1" runat="server"        ImageUrl="~/images/contoso.png" />     
<asp:Timer ID="Timer1" runat="server"       Interval="5000" ontick="Timer1_Tick">     </asp:Timer>         
</ContentTemplate> 
</asp:UpdatePanel>

Programming is Easy…..

Asynchronous requests in jQuery

As per my last post (What is Ajax ?), we have seen that the base of each asynchronous request is XmlHttpRequest object.

Now, Let’s look at the equivalent jQuery code for make synchronous and asynchronous requests.

jQuery offers an .ajax() method and various shorthands for accomplishing common tasks using AJAX.
Here’s the jQuery code:

 

$.ajax("google.com") // issue a 'GET' request to fetch google.com's home page
 .done(function(data) { // success handler (status code 200)
 console.log(data);
 })
 .fail(function(xhr) { // error handler (status code not 200)
 console.log("Error occurred: ", xhr.statusText);
});

The first line specifies the URL from which you want to request data. The code then specifies the callback
functions for the success and error conditions (jQuery takes care of checking for readyState and the status code).
Here we have not specify the type of request (GET) or whether it is asynchronous or not.
This is because jQuery uses GET by default and $.ajax() is asynchronous by default.
We can override these parameters (and more) to fine-tune your request:

 

$.ajax({
	url: "www.xyz.com",
	async: true, // false makes it synchronous
	type: "GET", // 'GET' or 'POST' ('GET' is the default)
	done: function(data) { // success handler (status code 200)
		console.log(data);
	},
	fail: function(xhr) { // error handler (status code not 200)
		console.log("Error occurred: ", xhr.statusText);
	}
});

For more info please visit:- http://api.jquery.com/jquery.ajax/

Note:- .done() and .fail() were introduced in jQuery 1.8. If you’re using an older version of jQuery, use .success() and .error(), respectively.

 

Programming is easy…

What is Ajax ?

AJAX stands for Asynchronous JavaScript and XML.

AJAX  is a technique that enables a page to request or submit data without doing a refresh or postback.

Using asynchronous requests to access data behind the scenes greatly enhances the user experience because the user does not have to wait for the full page to load.  And since the full page doesn’t have to reload, the amount of data requested from the server can be significantly smaller, which results in even faster response times.

The heart of AJAX is the XmlHttpRequest object, which was originally developed by Microsoft for use in Outlook Web Access with Exchange Server 2000. It was soon adopted by industry heavyweights such as Mozilla, Google, and Apple and is now a W3C standard (http://www.w3.org/TR/XMLHttpRequest/).

An  AJAX request with XmlHttpRequest looks like this:-


 //Instantiate XmlHttpRequest object
 var xhrObject = new XMLHttpRequest();  //Line 1

 // open a new 'GET' request to fetch www.xyz.com's home page
 xhrObject.open("GET", "http://www.xyz.com/", false); //Line 2

 //send the request with no content (null)
 xhrObject.send(null);  //Line 3

 if (xhrObject.status === 200) { //Line 4
 // The 200 HTTP Status Code indicates a successful request will output reponse text to
 //browser's console (Firefox, Chrome, IE 8+)
    console.log(xhrObject.responseText);
 }
 else {
     //something bad happened, log the error
     console.log("Error occurred: ", xhrObject.statusText);
 }

This example creates a synchronous request (the third parameter in xhrObject.open()), which means that the browser will
pause the script execution until the response comes back. You typically want to avoid these kinds of synchronous
AJAX requests at all costs because the web page will be unresponsive until the response comes back, resulting in
a very poor user experience.

But It’s quite easy to switch from a synchronous request to an asynchronous request : by simply set the third parameter in xhrObject.open() to true. 

Now, because of the asynchronous nature, the browser will not stop; it will execute the next line Line -4 (the xhrObject.status check) immediately. This will most likely fail because the request may not have completed executing.  To handle this situation, you need to specify a callback—a function that gets called as soon as the request is processed and a response is received.

Let’s look at the modified code now:

// Instantiate XmlHttpRequest object
var xhrObject = new XMLHttpRequest();

// open a new asynchronous 'GET' request to fetch www.xyz.com's home page
xhrObject.open("GET", "http://www.xyz.com/", true);

// attach a callback to be called as soon as the request is processed
xhrObject.onreadystatechange = function (evt) {

// as the request goes through different stages of processing, the readyState value will change  this function will be called every          //time it changes,  so readyState === 4 checks if the processing is completed

   if (xhrObject.readyState === 4) {
     if (xhrObject.status === 200) {
        console.log(xhrObject.responseText)
     }
     else {
         console.log("Error occurred: ", xhrObject.statusText);
     }
    }
};

// send the request with no content (null)
xhrObject.send(null);

This code is almost identical to the synchronous version, except that it has a callback function that gets
executed whenever the server sends back any information.

Note-You must attach any callbacks before issuing xhrObject.send(), or they will not be called.

Programming is easy….