In this article I will explain how to call JavaScript function after AJAX UpdatePanel Refresh or Partial PostBack (Asynchronous request) in ASP.Net.
In order to call JavaScript function after AJAX UpdatePanel Refresh or Partial PostBack (Asynchronous request), the AJAX PageRequestManager endRequest event handler will be used.
Concept
In order to call JavaScript function after AJAX UpdatePanel Refresh or Partial PostBack we need to determine when the AJAX UpdatePanel Refresh or Partial PostBack (Asynchronous request) is competed.
Call JavaScript function after AJAX UpdatePanel Refresh (Partial PostBack)
The below HTML Markup consists of an ASP.Net UpdatePanel containing a Label and a Button. Inside the window.onload event handler, I have called a JavaScript function to display Current Time in the Label.
Now whenever the AJAX UpdatePanel Refreshes or does Partial PostBack I need to update the Current Time displayed in the Label.
To achieve my target, I have called the JavaScript function for displaying time inside the PageRequestManager endRequest event handler.
Now whenever I am clicking the Button, a Partial PostBack is occurring and once the Asynchronous request is over, the JavaScript function is called which displays the Current Time.
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:Label ID="lblTime" runat="server" />
<asp:Button Text="Do Postback" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
<script type="text/javascript">
window.onload = function () {
DisplayCurrentTime();
};
//On UpdatePanel Refresh
var prm = Sys.WebForms.PageRequestManager.getInstance();
if (prm != null) {
prm.add_endRequest(function (sender, e) {
if (sender._postBackSettings.panelsToUpdate != null) {
DisplayCurrentTime();
}
});
};
function DisplayCurrentTime() {
var date = new Date();
var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
time = hours + ":" + minutes + ":" + seconds;
var lblTime = document.getElementById("<%=lblTime.ClientID %>");
lblTime.innerHTML = time;
};
</script>
Screenshot
Browser Compatibility
The above code has been tested in the following browsers.
* All browser logos displayed above are property of their respective owners.
Demo
Downloads
Download Code