How do I cancel a server request via javascript? (not an AJAX) - javascript

I am trying to make a button cancel a document request from the server while it is loading, I've tried window.stop() on Chrome but it does not prevent the page from reloading. I've also tried those lines but they get me back a blank page, which is not what I want, I need just to stop the request, as if pressing the Esc key.
document.write('<script type="text/undefined">'); or
document.write('<!--');
When I click the button and immediately press the Esc key I get the result wanted
edit: coming back to this question after some time, what I meant was actually:
"How do I prevent a request from loading the response sent by the server in user side"

We really need to see the code you are using to initiate the "document request from the server".
Here is a cool way to cancel if you are doing this type of request.
What about using abortable-fetch.
Nice demo here.

The solution to my problem was redirecting to:
http_response_code(204);
So the page stayed as it was before making the new request and but I was still able to use it normally. Thanks to those who answered anyways, the abortable fetch was also an solution.

Related

Saving data on `beforeunload` in IE11

I am trying to save user changes to a form on the server with AJAX on tab/window close.
This is a similar question:
Intercept page exit event
I am using this code :
$(window).bind('beforeunload', beforeUnload);
...and it seems to work fine except for when using IE11.
It seems that when the user verification alert pops up in IE11, every JS piece of code that was previously running gets halted (and my data is not sent over the wire).
So, if the user chooses to leave, everything is gone.
Has anybody made it work on that browser?
Is it possible?
EDIT :
I see now that it works sometimes and it fails on others.
When it fails, it starts the AJAX call (it hits the breakpoint at that point), but never gets in the success/fail function... (and I see nothing being sent when using Fiddler)
In summary, it first hits the AJAX call breakpoint, it then displays the confirmation dialog, and when you choose to leave the page nothing gets sent... :(
Turns out that this method of saving data is not reliable and it is working only by pure luck.
Also, the synchronous XHR is marked as deprecated by now, so it's not a good idea to use that either.
So, I guess the web is not meant to work this way...

Sending post request on window unload event (AJAX request Vs Form submit Vs Image request)

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.
Sending a post Request with Javascript on unload/beforeunload. Is that possible?
Ajax request with JQuery on page unload
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.
How to make form submission synchronous?
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.
Try this technique:
$.post('log.php', {hello:'world'}, function() {
sleepy.abort();
});
var sleepy = $.ajax({
url: '/sleep.php',
async: false,
});
Navigator.sendBeacon() is just what you need ✨
For more about Navigator.sendBeacon(), you should check Millennial JS or a helpful google dev article :D

How to append parameters to URL before page starts loading?

In Chrome, I'm looking to detect in a page URL is going to be on example.com's domain, and if it is, before loading, append foo=bar as a parameter and load that instead.
I've found that I can access when the Omnibar has been submitted here, but it seems like it'd load the original URL anyways, and while that's alright it's twice the bandwidth I feel is necessary. It's not a problem when it's only one page, but it's a change that needs to happen on every page in an site, so double the bandwidth definitely becomes an issue.
Currently, it works to detect if the URL is going to be example.com and is submitted, then call window.stop() and then set location.href to example.com/&?foo=bar but that doesn't seem ideal.
In short, the user goes to http://www.example.com and then the script changes it to http://www.example.com/&?foo=bar before loading the original link.
Take a look at the chrome.webRequest API, in particular the following method:
onBeforeRequest (optionally synchronous)
Fires when a request is about to occur. This event is sent before any TCP connection is made and can be used to cancel or redirect requests.
You can use
window.location.search = "foo=bar"
may be this helps.

Submit Old Google Form then redirect to another page

I am utilizing a Google Form on a webpage. I copied the source code from the form directly onto my page so that I can modify some of the HTML instead of using an iframe. Then instead of taking the user to the google docs response page I would like to redirect them to another page.
The trouble that I am running into is with the page redirect. I was able to get this working properly in Chrome and Firefox with this:
<form target="GoogleResponse" action="https://docs.google.com/spreadsheet/
formResponse?formkey=xxxxxxxxxxxxxxxxxxxxxxxxxx&ifq;" onsubmit="
window.location = 'targetPage.html';" method="POST" id="ss-form">
IE and Safari both did the redirect automatically and the response never got written to the Google Form. If I drop the redirect, the action works perfectly in both and the response is recorded in the Google spreadsheet.
So I attempted to pull the action out and instead did it everything in onsubmit instead, like so:
<form target="GoogleResponse" onsubmit="this.action = https://docs.google.com
/spreadsheet/formResponse?formkey=xxxxxxxxxxxxxxxxxxxxxxxxxx&ifq';
window.location = 'targetPage.html';" method="POST" id="ss-form">
Same problem as before, IE and Safari both redirect, and nothing is written to the Google spreadsheet. And once again, if I remove the redirect the response gets recorded in all browsers. I can also do other stuff like throw in an alert after the action, and everything continues to work fine. The only time I see the issue is with the redirect.
So at this point the only thing I can figure is that their is some sort of conflict between the redirect and the action. I have pretty limited working knowledge of javascript and forms so any help or recommendations would be greatly appreciated!
Sounds like the browsers have not complete the form submission before handling the redirect. onsubmit happens before the submission itself so you can not handle the issue there.
Use the onload function of the target iframe for the redirect.
This has been asked in similar manner:
Old Google Form redirect after submission
Take a good look at the answer. The onload function of the iframe will handle the redirect, so the redirect will not happen until the submission is complete and a response has been given from google. So when the hidden response from google is loaded we fire a redirect. This is async functionality between the client and server. We are waiting for the server to handle the data before redirecting.
Extended note: You could try putting the redirect within a setTimeout function. This would delay the execution of the redirect, allowing the server to handle the submission first. But setTimeout requires a fixed amount of time, so if the data handling is not synchronous (ie. asynchronous) setTimeout will not work as it may fire to early or too late. Asynchronous data handling applies when the data processing requires an undetermined amount of time (such as http requests).

Is there any possibility how to send an AJAX after close the browser window? [duplicate]

This question already has answers here:
JavaScript, browsers, window close - send an AJAX request or run a script on window closing
(9 answers)
Closed 6 years ago.
Is there any possibility how to send AJAX after close the browser window?
I have a browser game with movement in JavaScript (jQuery) and if I send Ajax after each movement it would be difficult for the server. So I want to send one AJAX when user close the window (or bookmark).
It must be functional in all modern browsers.
Thank you for answers
I'd suggest you update the server on some sort of timer so the server never gets too far behind in knowing what state the client is in (perhaps every 60 seconds when the client is active), pausing server updates when the client is not active.
Then, in your user interface, put some obvious user interface elements for Close or Stop that encourages the user to shut-down that way and then update the server when either of those buttons are hit.
Then, you can also hook the unload event for the page and send one last ajax call then. But, this is not called in every case or supported in all browsers so this would be done in addition to the two previous techniques.
I don't think there is a practical way to do it... but there is definitely a solution to your problem.
You can send your request either at some time interval or when the game arrives at a particular stage.
We're not seeing the complete scenario so please evaluate a bit more so I or someone else can help.
If possible.. I would add a "Save State" or just "Save" button. So the user knows that if he doesn't hit "Save" nothing will be "Saved".
You can try window.onbeforeunload e.g.:
function saveGame(e) {
if (!e) e = window.event;
//Ajax here
}
window.onbeforeunload = saveGame;
You can't send any ajax request after closing browser window. But you can use onUnload event for send ajax request when user click close button of the window.
I can suggest this:
invoke window.onunload (pay attention to firefox!) and store the current location in the server. important: make this async call.
in the server save the state of the user (leaving a page)
write a code in the global request event handler and query this state.
you can launch threads in the server to invoke the final unload (say, after 5 sec) no new request from the client
I know these steps are hard to implement, but they address your problem and solves it.

Categories