Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cancel a PHP process, when ajax call is cancelled?

i am currently working on a CRM system with a huge database. If the user wants to search a customer, he can use the ajax search. Everytime he changes something in the search field, while a call is pending, the old call is cancelled and a new one will be send to the server. My problem is, that the php processes on server side continue running. So if the user starts typing in an address, several requests are started and cancelled and the server needs more and more time to answer.

Is is possible to cancel the running php process, when the ajax call is cancelled? Or is there a possible solution on server side, to detect if a search request from the same user is running and cancel it before starting the new one?

Thanks in advance for your answers.

like image 963
Tobias Golbs Avatar asked May 29 '13 09:05

Tobias Golbs


People also ask

How to cancel an Ajax request that is already sent?

Sometimes you might want to cancel the ajax request that is pending from long time or want to cancel request if user accidently clicked submit button. In that cases, so you can just use abort () method. If the request has been sent already, this method will abort the request. See the below example.

How do I cancel a request in Python?

In order to cancel a request, we need a cancel token, which is a reference to the request call. If we store it in a variable, we will be able to use it to cancel the request whenever a new one is triggered.

How to check if Ajax request is valid or not?

Step 1. First of all check request is AJAX request or not. Step 2. Check Referer : Give response only when AJAX request is from your own url Step 3. Use Post Method in AJAX Always Use Post method while sending request and check $_POST variable before giving response

How to make secure Ajax request?

So, in this tutorial we will see how to secure ajax request or how to make secure Ajax call Step 1. First of all check request is AJAX request or not. Step 2. Check Referer : Give response only when AJAX request is from your own url Step 3. Use Post Method in AJAX


1 Answers

Your server side php has to output something to detect the request is canceled. But as you are likely performing a lengthy sql query, you can't output anything.

But still you can save your connection id into a session, and kill the connection if it's detected:

  1. Open session
  2. Open sql connection
  3. If search_connection_id is set in session, kill the connection
  4. Find your connection id, save in session as search_connection_id
  5. Close the session - important, else the next request will be blocked in step 1
  6. Query database
  7. If connection is broken, it's another search killing you in step 3, exit
  8. Open session, remove search_connection_id
  9. Send response, close sql connection
like image 138
Marek Avatar answered Oct 14 '22 14:10

Marek