ASP.NET AJAX: How to call client-side Javascript once an UpdatePanel request is over

The UpdatePanel control in Microsoft’s ASP.NET AJAX, is a good way to save some time when you have simple AJAX programming needs to post data to a form without refreshing the Web page.

However, once the asynchronous post has been executed, you might want to execute some Javascript after the request. In my case, my form’s controls where to be used to control a Google Map. Every time the form was updated, I wanted to refresh the map to reflect the data changes.

The trick is to add an “end request” handler to the request manager using:

    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);

where EndRequestHandler will be your handler function. In this function, you can also detect errors.

Here’s a simple example of a form with 2 TextBox controls where you enter text into one textbox and the server returns the length of the text in the second textbox. Then, when the server is done, the Javascript handler is called to display an alert.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DemoJScriptUpdate.aspx.cs" Inherits="CharterWeb.DemoJScriptUpdate" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    protected void txtDataOnChange(object sender, EventArgs e) {
        txtLength.Text = txtData.Text.Length.ToString();
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Client-side Javascript call after an UpdatePanel asychronous request</title>
</head>
<script type="text/javascript">
function EndRequestHandler(sender, args) {
   if (args.get_error() == undefined)
       alert("Your text has: " + document.getElementById("txtLength").value + " character(s)");
   else
       alert("There was an error" + args.get_error().message);
}
function load() {
   Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
}
</script>
<body onload="load()">
    <form id="form1" runat="server">
    <asp:ScriptManager ID="_scriptManager" runat="server" />
    <div>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
           <ContentTemplate>
              Write something: <asp:TextBox ID="txtData" runat="server" AutoPostBack="true" OnTextChanged="txtDataOnChange" /><br />
              Server says the length is: <asp:TextBox ID="txtLength" runat="server" AutoPostBack="true" />
           </ContentTemplate>
        </asp:UpdatePanel>
    </div>
    </form>
</body>
</html>

If you want to learn how to have more control over error handling, I recommend reading: “UpdatePanel: having fun with errors“, an excellent post by Luis Abreu.