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: 102920
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
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
                <asp:Button ID="Button1" runat="server" Text="Button"/>
            </ContentTemplate>
        </asp:UpdatePanel>   
   
    </div>
    </form>
</body>
Just below the </body> tag, add the following script
<body>
...
</body>
    <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;
        }
 
        Sys.Application.add_init(appl_init);
 
        function appl_init() {
            var pgRegMgr = Sys.WebForms.PageRequestManager.getInstance();
            pgRegMgr.add_beginRequest(BeginHandler);
            pgRegMgr.add_endRequest(EndHandler);
        }
 
        function BeginHandler() {
            beforeAsyncPostBack();
        }
 
        function EndHandler() {           
            afterAsyncPostBack();
        }
 
       
    </script>
</html>
 
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 
 
Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles
Suprotim Agarwal, ASP.NET Architecture MVP, MCSD, MCAD, MCDBA, MCSE, is the CEO of A2Z Knowledge Visuals Pvt. He primarily works as an Architect Consultant and provides consultancy on how to design and develop .NET centric database solutions.

Suprotim is the founder and primary contributor to DotNetCurry, DNC .NET Magazine, SQLServerCurry and DevCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls. and is authoring another one at The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal


Page copy protected against web site content infringement by Copyscape


User Feedback
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?

Sincerely,

- 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.
                                 Thankyou.
Comment posted by Eyal on Friday, September 17, 2010 9:39 AM
hi,

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


njnjn
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
S.Arun
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!!!

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel