8

I am using the __doPostBack method to refresh the UpdatePanel in javascript. I just want to wait for the update panel to get updated and then execute the subsequent javascript code. How do I wait on an asynchronous method to complete before I proceed further with execution (like in my case the asynchronous method is __doPostBack)? I want to simulate something like the way it is doing in C# using Thread.Join() method.

surajnaik
  • 725
  • 2
  • 10
  • 26
  • @anu Thanks for your response but can you give me an example? – surajnaik Jun 28 '11 at 10:35
  • [this](http://www.webdeveloper.com/forum/showthread.php?t=130767) will give you an idea – Anupam Jun 28 '11 at 10:46
  • actually i didnt notice earlier that you are using asp.net(of which i hav no idea). So, is there any callback function available for your asynchronous method.If yes, then you can put your subsequent js code inside that function or call some other function containing the remining code from that callback function – Anupam Jun 28 '11 at 11:18

2 Answers2

21

Use the Sys.WebForms.PageRequestManager endRequest event:

<script type="text/javascript" language="javascript">
    function clearPostBack() {
        $get('__EVENTTARGET').value = $get('__EVENTARGUMENT').value = '';
        Sys.WebForms.PageRequestManager.getInstance().remove_endRequest(clearPostBack);

        // TODO: anything you want after __doPostBack
    }

    function myPostBack(eventTargetUniqueId, eventArgument) {
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(clearPostBack);
        __doPostBack(eventTargetUniqueId, eventArgument);
    }
</script>
Pavel Hodek
  • 14,319
  • 3
  • 32
  • 37
user423430
  • 3,654
  • 3
  • 26
  • 22
3

Here is a much better way, which allows you to do something in case of successfull request and/or error:

$.ajax({
        type: "POST",
        data: 
        {
            '__EVENTTARGET': '<%=YourButtonName.ClientID %>'
        }
    }).done(function (data) {
        alert("ok");
    }).fail(function (p1, p2, p3) {
        alert("error");
    });
  • 3
    I like this way but sadly this is not a postback. It's a fresh call. So if you have values in the viewstate you will not have them available on the server side. – Vortex852456 Oct 24 '16 at 12:52
  • Sys.WebForms.PageRequestManager is the right choice if you have an UpdatePanel, but this is a great solution otherwise – Sue Maurizio Dec 31 '21 at 07:43