I want to open a window, make an ajax call and close the window.
I want to do it as fast as possible and i was wondering if i have to wait for the ajax response before closing the window?
Currently i’m doing it like this:
$.ajax({
url: requestURL,
type: 'GET',
dataType: "json",
cache: false,
timeout: 30000,
always: function () {
closeWindow();
}
});
However, i was wondering if the ajax will reach the server 100% on all browsers if i will do it like this:
$.ajax({
url: requestURL,
type: 'GET',
dataType: "json",
cache: false,
timeout: 30000,
always: function () {
}
});
closeWindow();
//THIS HAS CONFIRMED TO NOT WORK AND MISS OUT SOME REQUESTS
closeWindow()
implementation is irrelevant.
The full usecase is as follows:
- I send a user a link on Whatsapp/Telegram/Messenger
- User clicks the link
- Browser is open -> issue an ajax call -> closing the window.
EDIT
To clarify, i don’t care what was the server response for the call. I just want to make sure that the browser issued the HTTP GET to the server and then close the window.
EDIT 2
AJAX is not a must, also, better to use vanilla JS
5
Answers
I guess the answer was at the back of my head: use an Image object to send the request and close the window right after:
Since you are using JQuery, you can use the “done” callback option, and set your function inside so the window will close if the request was successful.
You can also use the “fail” callback option to manage potential errors.
You can do it like you said, send the ajax request and close the window, since it’s async methods, it will make the call, if you wanna be absolutely SURE, write a little PHP script that writes something in a file with a little sleep at the top to check that it made the call, but it will do it.
Edit : or use this method and close the browser in the done function, it will take 1ms or so
following function can close your tab after 1 sec, without waiting for the ajax response
I believe that if you want to know when your request was launched you could use
.ajaxStart
as explained here.Or you could try some raw js like the solution explained here.