Any way to do a synchronous PageMethods call?

user724198 picture user724198 · Jul 14, 2011 · Viewed 16k times · Source

I'm trying to do this:

function DelBatch()
{var userInfo = get_cookie("UserInfo");
PageMethods.DeleteBatchJSWM(userInfo, function(result)
                                          {window.location = "BatchOperations.aspx";});
}

But it still runs asynchronously. I need the browser to actually wait until my code-behind is finished executing, then it can be refreshed

There's a listbox loaded with values that were just deleted from the database, they shouldn't be visible. Problem I have is the window location refreshes before the code-behind is executed, and nothing seems like it was deleted to the user.

Answer

James McCormack picture James McCormack · Jul 14, 2011

Call it using jQuery ajax instead? It features an option (async) where you can select sync/async mode: http://api.jquery.com/jQuery.ajax/

This excellent article tells you how best to call PageMethods from jQuery: http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/

Essentially, all you will need to do is this:

$.ajax({
  type: "POST",
  async: false,
  url: "yourpage.aspx/DeleteBatchJSWM",
  data: "{ put json representation of userInfo here }",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(msg) {
    window.location = "BatchOperations.aspx";
  }
});

Look at Crockford's JSON stringify for a json formatting solution.