Using beforeunload to execute task before page exit - javascript

I'm trying to get an action executed before page leave, this requires a GET request being executed.
I would like to give the GET request at least 50-100ms in order to get the request forwarded to the web server.
I'm capturing the beforeunload action using:
$(window).bind('beforeunload', function() {
send_data();
});
Any tips?

You have the highest chance to get your request sent if you make it synchronous (async: false in the $.ajax() options if you are using jQuery).
But you cannot be sure it always gets through..

You should prevent default action with event.preventDefault().
Note that not every browser support beforeunload

Related

Are XHR requests created in an anchor tags click handler guaranteed to be sent?

I'm sure this information exists out there but my googling abilities are failing me here.
What I want to know, is if I trigger a XHR request in an anchor tags click event handler, is that request guaranteed to be sent? I don't care about handling the response, but I don't know if it's possible for the request to never leave the unsent state before navigating away.
For example, say I want to track all anchor tag clicks so I do something like this:
$("a").on("click", () => $.ajax({ url: "/track_link_click", method: "POST" });
Is there a situation where the request in the event handler never gets sent? I could prevent the location change from taking place until response is received but I'd much rather not.
Thanks in advance!
There's no guarantee, by design, but in practice I'm pretty sure all browsers will at least get the request sent away.
I suggest you look into navigator.sendBeacon() which is designed for exactly this type of thing. Its purpose is to guarantee that the request gets sent even if it has to happen after the page unloads.
https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon
It's not supported in IE and not yet in Safari, so you'll need to rely on the regular AJAX method as a fallback.

Aurelia stop overload of http requests

I'm using Aurelia and have multiple promises calling my API. If I continually click the button to fire the promises over and over and over again the back end will timeout. How can I stop/halt the promises I am firing and just get the newest one so as to not over work the API and cause a timeout?
This is not specific to aurelia, it happens with any asynchronous event implementation.
When you click on a button, the event handler is called.
The event handler sends an asynchronous AJAX request to your server. Because it's async, your code and your application continues to run while the request is happening.
User can click again on the button and a second AJAX request can be sent at the same time, assuming that you click faster than requests complete.
To make it worse, concurrent requests may even complete out-of-order (i.e. a later request completes before a former). Your code should be prepared to handle that properly.
If you don't want this behaviour, it is up to you to prevent the user from submitting again until the AJAX request completes. For example you could:
Disable the button when sending the request; or
Display a modal "loading" screen / spinner to prevent any interaction with the application while the request is in flight.
Note that giving user feedback is good UX anyway. A network request might be delayed for a whole lot of reasons and it is a good idea to give some feedback to let him know that something is happening.

Jquery async call not working on user event

In my webpage many on-load ajax call those works fine.
Action takes time as per processing time. Means if any action that has been complete will send response and will not wait for first to finish.
But if same I am trying to do with on-lick or any user event. All ajax call works synchronously. I want these should not wait to finish the execution of first running action. All should start and complete independently.
I am using jquery 1.8 where default async= true;
Please help me here to resolve this.
Issue may be due to session lock.
more detail you can find it here
http://php.net/manual/en/function.session-write-close.php
call session_write_close function if there no session write activity in your script or function.
Such issues are observed in many concurrent ajax call and previous call has some session write activity. In this case session will be locked until it completed its execution.
If you set async to true, they will all fire at the same time.
make explicitly declaration of async = true option in each ajax call .
Useful jsfiddle link
http://jsfiddle.net/jquerybyexample/tS349/

jQuery: How to call a function before unload window

I want to call a function before closing a window.
For example I want to call ajax before closing page. I am using following code but its not working.
$(window).bind('beforeunload', function(){
$.ajax({
url:'logout.php',
type:'POST'
});
});
What is the best way to call function before closing the window?
You code is most likely being run, but as it starts a asynchronous ajax request and the browser tears down the page immediately after triggering onbeforeunload, the request probably never gets sent (or if it gets sent, probably gets aborted).
The event handler for onbeforeunload is only allowed to do a very limited set of things (and the list varies from browser to browser, and the list frequently changes as browsers update things). For that reason, using onbeforeunload for anything other than the one purpose for which it was intended, giving you a last ditch chance to warn the user of losing information by leaving the page, is not a good idea.
The code you have written just makes an ajax call, but even before the call can be made, your window will be exit. And even if the request is sent, it may be aborted in between.
Try this code:
function WinClose() {
$.ajax({
url:'logout.php',
type:'POST'
});
return false;
}
window.onbeforeunload = WinClose;
Write this code in <head>

Sync AJAX for specific case

I have 3 buttons on page.
Each one makes AJAX request by clicking on it.
These all requests should makes in async mode.
But clicking on any button in second time should:
1. Stop current request which was made clicking on this button at first time.
OR
Do Nothing.
Option#1 is prefer.
I know about abort(), but my question - how to detect that Ajax request (from certain button) is still not finished ? Here the main point is - request from certain button. I do not want stop all ajax requests. I want stop only request which was made by clicking in the same button at first time.
In my project i'm using jQuery
is this http://api.jquery.com/category/deferred-object/ can help me ? if yes can you provide any suitable example ?
Thanks
I don't believe deferred objects will do what you want. They're designed more for doing promises and aggregate callbacks. You can look into the state of an ajax call by keeping a reference to the jqXHR object returned by $.ajax though.
var ajax;
function onClick() {
if (!ajax || ajax.state() === "resolved") {
ajax = $.ajax(url);
}
}
you need to have a variable associated with each possible ajax process, which tracks whether that process is currently running. When an ajax call starts, set that variable to indicate it's running. When that ajax call completes, set the variable to indicate that the process has stopped. Then, when the user clicks the button, you can examine the variable to decide whether you need to abort() the ajax call or not.

Categories