Executing ClientScript Before and After an Asynchronous PostBack using ASP.NET AJAX

Posted by: Suprotim Agarwal , on 1/13/2009, in Category ASP.NET AJAX
Views: 166510
Abstract: A user recently mailed me to find out if there is a way to determine, when an asynchronous postback begins and ends in an ASP.NET AJAX page. He wanted to fire some JavaScript code during these events. Here’s how to determine the events.
Executing ClientScript Before and After an Asynchronous PostBack using ASP.NET AJAX
A user recently mailed me to find out if there is a way to determine, when an asynchronous postback begins and ends in an ASP.NET AJAX page. He wanted to fire some JavaScript code during these events. Here’s how to determine the events.
During the AJAX client-side execution cycle of a page containing the ScriptManager control, the Application.init event is raised when the page is requested for the first time. We can use this event to wire up the client events that occur during an async postback. For this purpose, we use the Sys.WebForms.PageRequestManager class that raises client events specific to asynchronous postbacks.
Now the beginRequest and endRequest events of the Sys.WebForms.PageRequestManager class are raised before an async request and after an async response respectively. We will use these events to execute our JavaScript code as demonstrated below.
Note: I am using Visual Studio 2008 and thereby utilizing the ASP.NET AJAX plumbing that comes along with it.
Open VS 2008. Click File > New > Website. Choose ASP.NET Website from the list of installed templates, choose target platform as .NET Framework 3.5, choose the desired language and enter the location where you would like to store the website on your FileSystem. I have created a folder called VS2008 Projects, so the location over here is C:\VS2008 Projects\ ExecuteClientScriptDuringAsyncPostback. After typing the location, click OK.
Open Default.aspx. Switch to the Design mode of Default.aspx. Open the toolbox (Ctrl+Alt+X). Now add a <ScriptManager> control to the page and then an <UpdatePanel>. Inside the <UpdatePanel>, add a label and a button control as shown below
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
                <asp:Button ID="Button1" runat="server" Text="Button"/>
Just below the </body> tag, add the following script
    <script type="text/javascript">
        function beforeAsyncPostBack() {
            var curtime = new Date();
            alert('Time before PostBack:   ' + curtime);           
        function afterAsyncPostBack() {
            var curtime = new Date();           
            document.getElementById('Label1').innerHTML = 'Time after PostBack:    ' + curtime;
        function appl_init() {
            var pgRegMgr = Sys.WebForms.PageRequestManager.getInstance();
        function BeginHandler() {
        function EndHandler() {           
As described above, we use the Application.add_init() to add the beginRequest and endRequest event handlers. To add or remove handlers for events raised by the PageRequestManager classes, use the add_eventname and remove_eventname methods of those classes.
Inside these handlers, we call our JavaScript functions beforeAsyncPostBack and afterAsyncPostBack respectively.
That’s it. Run the page. When you click on the button, just before an Asynchronous request, the beforeAsyncPostBack() gets executed.
Before Async
Similarly, after an Asynchronous response, the afterAsycPostBack() gets executed.
After Async
I hope you liked the article and I thank you for viewing it.
If you liked the article,  Subscribe to my RSS Feed or Subscribe Via Email 

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn

Page copy protected against web site content infringement 	by Copyscape

Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Shuaib on Tuesday, January 13, 2009 9:09 AM
Terrific, you guys are doing an awesome job! Keep it up!
Comment posted by Nice, but limited? on Wednesday, January 14, 2009 9:44 AM
Hi there.

Great code! Just one thing. Is there any way to execute a clientscript after postback for one button and not postback for another?


- Oystein Saebo -
Comment posted by ravikumar on Monday, January 26, 2009 10:02 AM
It's very very very............ helpful for all beginers who wanna get start with AJAX
Comment posted by Machibest on Friday, April 24, 2009 11:09 AM
Thank you so much for this!
I was rounding desperation.. lost literary hours looking for this code!
I believe forcing a js code execution on return of a partial post back should be done much simpler! This is why I hate asp.net controls.. I would encourage people to using AJAX through any js library such as Jquery, Prototype, Dojo or whatever.. send and receive json for data transportation between client-server.. take control over things! Don't let asp.net produce js code for you: it will suck, will be buggy, and worst off all, it will be out of reach for easy-tweaking.

Anyway, thank's a lot for this excelent article! Was really clear and simple. :-D
Comment posted by Maikel Morkos on Friday, April 24, 2009 8:03 PM
Great tip!!! This is very helpful. You are awesome!
Comment posted by Suprotim Agarwal on Monday, April 27, 2009 9:19 AM
Machibest, Maikel: Thanks for your feedback!
Comment posted by Rob on Tuesday, August 18, 2009 11:17 PM
It works great if I place all my Jquery functions in the afterAsyncPostBack function.  How do I load an external Jquery file into the page so that they run?
Comment posted by Rupendraonline on Friday, October 2, 2009 6:25 AM
i want to chack any example but i m not chak any example because every one zip example password predate so please  help me. solved my problam.
Comment posted by Eyal on Friday, September 17, 2010 9:39 AM

is there a way to know on the client javascript methods what was the trigger?

i want to set a progress animated gif (which is quite easy), but show it only incase of a specific trigger to the page (user action) otherwise (timer every 1 min) i dont need the progress bar?
Comment posted by Scott Smith on Friday, February 4, 2011 2:00 PM
Solution works for me.
Comment posted by Guillermo Ortiz on Monday, February 14, 2011 4:10 PM
Excelent! thanks a lot.
Comment posted by Rishi Saxena on Friday, April 1, 2011 7:26 AM
Comment posted by Natalie on Friday, June 1, 2012 5:43 PM
Thank you SO much for this post.  It was exactly what I was looking for!  Cheers!
Comment posted by Luciano Lorencini on Wednesday, August 1, 2012 11:28 AM
Take a look at THIS article, showing how to do this programatically in code-behind: http://www.dotnetcurry.com/ShowArticle.aspx?ID=200

This way you can know which control triggered the event, and works like a charm.
Comment posted by Midhun Balan on Thursday, January 23, 2014 5:32 AM
Good Article thank You very much...
Comment posted by Shubhangi on Thursday, April 17, 2014 1:25 AM
I have implemented updatepanel in my page and tried this code. I am calling ajax popup on click of linkbutton and after adding this code popup in not coming. Just blocked screen with a message "please wait".
Comment posted by sam s on Thursday, July 31, 2014 5:34 AM

Comment posted by arun on Wednesday, August 13, 2014 11:28 PM
loading progress bar when postback or page load in mvc4.
your help is very much support me ...

Advance Thanks
Comment posted by Jose on Wednesday, October 15, 2014 10:15 AM
Thanks a lot Master!
It works great!
Comment posted by Simmy on Monday, October 27, 2014 3:46 AM
Thanks! Exactly what I needed!!!