Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if a user exits the browser or changes page before an AJAX request is over

Tags:

I am calling a php script over ajax to do some database maintenance. If the user closes the page, hits back, or clicks a link, will the php script be fully executed? Is there a way to do it?

Maybe if the php script called the exec() method or something similar, which would in turn call a script via the console as such:

$ php /var/www/httpdocs/maintenance.php 

?

like image 205
NaturalBornCamper Avatar asked Jan 18 '12 20:01

NaturalBornCamper


People also ask

What happens when JavaScript makes an AJAX request in a browser?

When you make an AJAX request, your browser sends an HTTP request to a given address. The server on the other end of the request responds, and returns the data to your browser. This is the same thing that happens when you navigate to a new web page.

What is an AJAX request?

An AJAX request is a request made by an AJAX application. Typically, it is an HTTP request made by (browser-resident) Javascript that uses XML to encode the request data and/or response data.

How do I cancel my ongoing AJAX request?

ajax({ type: 'POST', url: 'someurl', success: function(result){} }); Then you can abort the request: request. abort();

How does AJAX work?

AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page. Classic web pages, (which do not use AJAX) must reload the entire page if the content should change.


2 Answers

It's a race condition. PHP will detect at some point (usually upon attempting to do output) that Apache is yelling in its face that the remote user has closed the connection. Whether everything you wanted to do is done at that point depends on how your code's structured.

If you want to ensure that all operations are complete before the script shuts itself down, use ignore_user_abort(TRUE), which keeps PHP running after the connection is severed. It's still subject to the user max_execution_time limits and whatnot, but it will not shut down because you disconnected.

like image 172
Marc B Avatar answered Sep 27 '22 19:09

Marc B


As long as the user agent (browser, etc.) has fully sent the request, the server has all it needs and will complete the request and try to send back a response.

In fact, this sort of "pinging" behavior is often used for "heartbeat"-like processes that keep a service warm or perform periodic maintenance.

like image 26
cdeszaq Avatar answered Sep 27 '22 20:09

cdeszaq