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:


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" "">
<script runat="server">
    protected void txtDataOnChange(object sender, EventArgs e) {
        txtLength.Text = txtData.Text.Length.ToString();
<html xmlns="" >
<head runat="server">
    <title>Client-side Javascript call after an UpdatePanel asychronous request</title>
<script type="text/javascript">
function EndRequestHandler(sender, args) {
   if (args.get_error() == undefined)
       alert("Your text has: " + document.getElementById("txtLength").value + " character(s)");
       alert("There was an error" + args.get_error().message);
function load() {
<body onload="load()">
    <form id="form1" runat="server">
    <asp:ScriptManager ID="_scriptManager" runat="server" />
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
              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" />

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.

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

  1. Warachot

    Thank ,I looking for this I see in your blog .


    From Thailand.

  2. Note that EndRequestHandler will be called on any callback. So it will be called on any control that those a call back

  3. CMG

    Awesome post. Thanks!

    I was trying to figure this out for the past 2 hours.

  4. Excellent…been looking for something similar

  5. Satchey

    Love you man!
    This one helped me to maintain scroll position in an updatepanel that was using a AsyncPostBackTrigger.

  6. Francisco

    Can anyone send me the code for maintaining the scroll position in an updatepanel that was using a AsyncPostBackTrigger? I tried lots of scripts but none of them worked right. Thanks in advance. My e-mail is

  7. Lizard

    I dont like it. A want to set from a server side what function or/and parameters to call on the client side after a callback. This is very simple solution.

  8. saravanan

    hi i am using updatepanel in my aspx form
    (asp 2.0) i cant display some messageboxes
    and i wrote the messagebox in server side
    using java script
    private void MessageBox(System.Web.UI.Page page,string Msg)
    string MsgScript = “<script language=’javascript’>alert(‘” + Msg + “‘)</script>”;

    if (!(ClientScript.IsStartupScriptRegistered(“MessageScript”)))
    ClientScript.RegisterStartupScript(typeof(string), “MessageScript”, MsgScript);
    messagebox action is going but not calling messages
    please help me

  9. Pran

    Thanks for the article.

  10. Andrew

    this code appears not to work in firefox.

    Its possible ive not set this up correctly, but first glances appear to not fire the event at all. No javascript error of any description, just nothing.

  11. I use it in a current project and it works in Firefox. There’s probably something in your code. Step into your code by installing Firebug.

  12. Found the post intersting. To add some more functionality, You can use the sender._postBackSettings.panelID property to identify the control which raised the click. This will avoid the EndRequestHandler called on any post back.

    something like

    if(sender._postBackSettings.panelID == “UpdatePanel1|LinkButton1”)
    alert(‘From LinkButton’);
    alert(“Some other control”);

  13. Carlo

    Thanks a lot for this blog. it helped me solve my problem!

  14. Aloine

    Cool man,thank you ,you resolved me a big problem

  15. cmeigs

    Very good article but what if I am using a Master Page and don’t have use of the body onLoad event? I need this functionality on one page in my website so I feel I cannot use the onLoad in the body tag. Is there another way to call client side script after UpdatePanel request is over?

    Thanks in advance,

  16. @cmeigs: well, you have 2 options:
    1) you could make the body in the Master page runat=”server”, give it an ID and programmatically add the onload attribute to the body from the child page by accessing the Master’s body object
    2) or much easier to maintain, you could use jquery and insert a Javascript call in your child page by adding:
    <script language=”javascript” type=”text/javascript”>
    // your onload code here

  17. Keith

    Re: but what if I am using a Master Page and don’t have use of the body onLoad event?”

    Use the DOM ready event instead of body onload. Several of the JS libraries such as JQuery or EXT.js make it easy to detect DOM ready

  18. ??????

    That was the thing I have needed so much!
    Great thanks.

  19. Mike

    very helpful 🙂

  20. AZ

    wow, you rock!!! thanks man

  21. David

    In answer to Keith. I have the same situation. You can add the same sort of logic to the Page_load of any control or part of the page using RegisterStartupScript. The example below fires a js event 200ms after every postback (ajax or not). You can remove the ajax/trad lines depending on what you want to handle.

    protected void Page_Load(object sender, EventArgs e)
    //This script handles ajax postbacks, by registering the js to run at the end of *AJAX* requests
    Page.ClientScript.RegisterStartupScript(typeof(Page), “ajaxTrigger”, “Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);”, true);
    Page.ClientScript.RegisterClientScriptBlock(typeof(Page),”EndRequest”, “function EndRequestHandler(sender, args){setTimeout(‘DoWhatever()’,200);}”,true);

    //And this is for *traditional* requests Page.ClientScript.RegisterStartupScript(typeof(Page), “tradTrigger”, “setTimeout(‘DoWhatever()’,200);”, true);

  22. Excellent article, added to bookmarks.

  23. Thank you…

  24. Very good job. Add your blog to bookmarks.

  25. thanks! Add your blog to bookmarks.
    realyy good job!

  26. Thank you….

  27. Hi, It’s wery important problem for my.
    thank you. it helped me.

  28. Chance

    I hate to be the guy with the bad news but this will not work in a very important scenario.

    Make two or three user controls. Then, during a button click or whatever postback control, try to swap UserControlA with UserControlB and so on. You will get a “‘null’ is null or not an object'” error. This pretty much breaks the entire client side Ajax framework. You will even get this error if you have all three user controls on the page and during postbacks, make one invisible. MSFT is something else. How could they not catch this.

  29. thanks youu::))

  30. Thank you 🙂

  31. anhvu

    Wow ,it’s cool man ,thank you .

  32. Ashish Lingwal

    Very good job. Thanks a lot.

  33. Sorry, forgot to thank you for a great preview. Thanks for stepping in at such short notice!

  34. Javier

    Great! Solved my iframe auto height adjust problem.

  35. it’s really excellent my dear

  36. TOm

    Thank you! I’ve been trying to figure this out for hours! Works like a charm.

  37. That’s great, I never thought about that like that before.

  38. Ixtlan

    I was looking an answer of how to call an script in javascript/jquery using ajax-update panel in the 2.0 framework and you got it. Your blog help me a lot, best regards and thankyou from NYC.

  39. seagoing

    Great stuff Jerome. I’ve spent two days trying to find the solution you’ve expounded on your blog. Many thanks

  40. Muhammed Mohiudeen

    Thanks,I’ve spent one full day to find the solution.Many thanks to you…

  41. rob

    This was the missing link@! thanks.

  42. thank you very much

  43. thank you

  44. thankss

  45. thanks you

  46. Viral

    Need to close web form used the java script of winclose() which use window.close();
    It works fine without update panel.

    I have submit and cancel button and need to close the form after everything updated.
    Update panel give me the problem while use of the Response.write(“<script=javascript”>;

    Any other way I can close the web form.

    Any help or suggestion will be great.


  47. thank you web admin’s

  48. Thank You…

  49. sagnik

    <%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %>

    <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “”>

    <html xmlns=””>
    <head runat=”server”>
    <title>Untitled Page</title>
    <script type=”text/javascript”>
    function EndRequestHandler(sender, args) {

    if (args.get_error() == undefined)
    if (document.getElementById(“TextBox1”).value==null )
    alert(“EMPTY BOX”);
    alert(“There was an error” + args.get_error().message);
    function load() {

    <form id=”form1″ runat=”server”><asp:scriptmanager runat=”server”></asp:scriptmanager>
    <br />

    <asp:UpdatePanel ID=”UpdatePanel1″ runat=”server”>

    <ContentTemplate >
    <asp:TextBox ID=”TextBox1″ runat=”server”></asp:TextBox>
    <asp:Label ID=”Label1″ runat=”server” Text=”Label”></asp:Label>
    </asp:UpdatePanel><asp:Button runat=”server” Text=”Button” onclick=”Unnamed2_Click” />
    plz hlp, ??? i want to do validation in update panel using javascript

  50. thank you kanka

  51. erkan ft seoking

  52. thank you dostum..

  53. Carlos

    Thanks for all, you have saved my life. Your blog is really interesting

  54. Ambuj

    You are like God to me this time .. i am very new to AJAX and ASP.Net and looking for the same thing from days … Thanks a lot …

  55. Wow, i saw thoose tags before, but i never tough they would become a microformat, shame if mf’s are used to spam. very bad thing!

  56. Sravan

    Thanks was looking for this!! Helped me a lot!!

  57. Lei

    Before this post, my already complicated jQuery will not work well with AJAX. Now, they happily live together!

  58. Duminda

    I’m using UpdateProgress with UpdatePanel. now the progress gets stuck after partial postback.

    How can I stop it?

  59. crypt

    Thanks for the solution , sadly find your blog after 4 hours.

  60. Jose Amado


    I used your sample to get the cursor position from the textbox (add_beginRequest),
    and between add_beginRequest and the add_endRequest i execute some functins that delay 10s.
    And in the end (add_endRequest) i try to preserve the cursor position in the textbox.

    but if the user write any text after (add_beginRequest) raises,
    the text that he wrote is delete after the (add_endRequest) ended…

    Could you help me with bug?


  61. nice thank you

  62. Claire Harrison

    Thank You!
    Worked like a charm.

    We are using jquery so added this into the $(document).ready section rather than body onLoad.

  63. Thanks dear, Its really a real solution, what I got.(May God bless you)

  64. ayhtut

    nice code…. thanks alot..

  65. I was looking an answer of how to call an script in javascript/jquery using ajax-update panel in the 2.0 framework and you got it. Your blog help me a lot, best regards and thankyou from NYC..

  66. Thanks a lot. Good information

  67. Ashok

    It works like a charm… Thanks a lot 🙂

  68. Very good *******

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>