I am trying to track user events happening on my site. One way to do this is send an ajax request every time you see an event. But this will unnecessarily load the server. One way to mitigate this problem is to send request in bulk on unload event(right now I have set a threshold of 16 events). But the problem arises during "unload/beforeunload" event.
The following are the problems I am facing:
- AJAX request does not work unless they are synchronous. But I need to use asynchronous as its counterpart could cause problems if the server response is slow. Most of the questions raised on this matter in Stack Overflow suggests you to use "sync". Some of them are given below.
I can use images. Well this method works fine (requests are logged) but its a GET request. I need POST request.
I can use a form with the result loading in a hidden iframe. This works fine (requests are logged) on Chrome (36.0.1985.125) but fails on Firefox (31.0).
But on Chrome I am facing a strange problem. That is, if I remove "target" attribute, the request is not being logged. Is "target" attribute necessary to initiate a request during "unload/beforeunload" event?
One of the Stack Overflow answer suggested that form submission is asynchronous. If that is so why does not browser cancel the request as it does for an AJAX request during "unload/beforeunload" event? and same question for images too.
The test code which I used is given below. I am using XAMPP server on MAC.
test.html Front end code.
test.php Backend code.