I ended up implementing my own function
CAjaxService.SomeMethodSync = function() {
...
}
where I do a manual synchronous post request. Not the most elegant method, but it works.
Question
I have a legacy WebService referenced in a ScriptManager
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/AJAX_SERVICE.asmx" />
</Services>
</asp:ScriptManager>
And defined like
<System.Web.Script.Services.ScriptService()> _
Public Class CAjaxService : Inherits System.Web.Services.WebService
<WebMethod(enableSession:=True)> _
Public Sub SomeMethod()
...
End Sub
...
End Class
After that to call the method from JavaScript client code I can simple do
CAjaxService.SomeMethod()
I need to execute this call when user navigates away from the current page, so I placed it into page unload event:
function pageUnload(sender, args) {
CAjaxService.SomeMethod()
}
The problem is - the call is async and page navigates away before call is complete (if I place alert()
after the call - it goes thru). I've seen similar problems with jQuery ajax calls (and recommended solution to make a synchronous call) but I am not sure if this is possible in MS Ajax.
What would be the way to execute (and complete) an AJAX call upon user navigating away from current page?
Solution 3
I ended up implementing my own function
CAjaxService.SomeMethodSync = function() {
...
}
where I do a manual synchronous post request. Not the most elegant method, but it works.
OTHER TIPS
You should attach to the onBeforeUnload
event instead of the onUnload
event.
The onUnload
event actually fires when the first byte of the next page is downloaded. At this time the entire context of the previous page starts to get destroyed, and there's a very low chance that you will be able to create network connections. The best that you could do at this point is set a cookie via JavaScript.
The onBeforeUnload
event, however, fires before the request for the next page is made, and you have enough time to make a network call to your server to pass it some information. Make your Ajax call within this method.
I try to reply your requirements I create a simple web service that sleep for 5 seconds
[WebService(Namespace = "http://tempuri.org/")]
[ScriptService]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class CAjaxService : System.Web.Services.WebService {
[WebMethod(true)]
public string SomeMethod() {
Thread.Sleep(5000);
return DateTime.Now.ToString(CultureInfo.InvariantCulture);
}
}
I try to call it synchronusly but the only way to do it using the MS Ajax Library is to extends the Sys.Net.XMLHttpExecutor you can see the post
I can make the page to wait in the unload event using jquery and make the ajax call synchronously with this code
<script src="Scripts/jquery-2.0.3.js"></script>
<script>
window.onbeforeunload = function () {
$.ajax({
type: "POST",
url: "CAjaxService.asmx/SomeMethod",
async: false,
});
};
</script>
I hope this will help you