Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cancel ajax request that has run (on server side)

I was wondering if there's a simple way to cancel an AJAX request?

Beyond just calling an 'abort' on the XMLHTTPRequest on the client side, is there a way to easily stop the server process? The server is using Apache.

Thanks

like image 506
AndreLiem Avatar asked Apr 28 '09 20:04

AndreLiem


People also ask

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 do you abort an Ajax call?

Just use ajax. abort(); } //then you make another ajax request $. ajax( //your code here );


4 Answers

For PHP I have found a way to stop or abort by using session_write_close();. Just put this after session_start() on your script. If you are using framwework or OOP then keep it as first line of your method. This happens because session data is locked until the ajax has finished.

Tested & saw another page is now loading after xhr.abort()

Solution hints found here Abort Ajax requests using jQuery

like image 170
Rejoanul Alam Avatar answered Sep 26 '22 06:09

Rejoanul Alam


No. There's definitely no simple way.

I can think of some complex ways, but they would be unreliable.

You'll probably have more luck developing a process for reversing the changes from a request you've just run (I'm assuming that's the reason you would want to stop it.)

like image 7
Steven Richards Avatar answered Oct 06 '22 10:10

Steven Richards


Initiate another Ajax request. I found this thread by trying to figure out how to prevent a previous request from being interrupted when another is called.

like image 4
dan Avatar answered Oct 06 '22 08:10

dan


there are no good ways to stop the request itself over the network (as many have said), but it's relatively easy to stop the effects of the request. i.e.

on the server-side: you could exit (or whatever term you'd require to kill the script) by constantly checking global variables (acting as flags) like cookies or sessions (again, assuming these would change during the execution of the script). additionally, you could keep files or database entries as flags (that you can poll for existence).

on the client-side: you could call abort (which doesn't work in all browsers, like others have said), or you could keep a global semaphore / flag at the top of your callback (that checks the global value to see if it should still execute or not). example:

 window.ajaxIsStillGood = true;

 xhr.onreadystatechange = function( )
 {
     if( 4 === xhr.readyState && 200 === xhr.status )
     {
         if( true === window.ajaxIsStillGood ){ /* still good */ }
     }
 }

 /* bad stuff happens */

 window.ajaxIsStillGood = false; // now the code won't execute
like image 1
Dan Beam Avatar answered Oct 06 '22 08:10

Dan Beam