Tip for Making Ajax Calls in window.beforeunload / window.unload especially if you are using Angular JS

If you are making Ajax calls in angular application in $window.beforeunload event, then there is high possibility that you will see the issue that the server side API which needs to be invoked as part of Ajax calls is not getting invoked.

Reason for this is, for making Ajax calls you will be using $http and all $http calls are async in nature, so browser will kill the thread before sending the request. $http internally uses below API

xhr.open(method, url, true);

The third parameter in an xhr.open() can be set to false or true, where false is synchronous and true is asynchronous. In the Angular case, it is hard coded to true, so that all outgoing calls will be asynchronous. So using $http is not a good choice in this scenario.

Instead of $http you can use $ajax from jQuery to make these Ajax calls, as $ajax provides an option to dictate if the request should be asynchronous or synchronous. It can be dictated with help of parameter async: false

$window.unload(function () {
        type: 'PUT',
        async: false,
        url: 'api/unlockcustomer?id=123'

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s