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

邮差的信 提交于 2019-12-21 03:53:49

问题


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.


回答1:


Are you looking for ignore_user_abort() ?

http://www.php.net/manual/en/function.ignore-user-abort.php




回答2:


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



回答3:


Thank you all for your answers.

I redesigned my search queries like Anigel suggested, with an overwhelming result.

But i think the correct answers to my question are the answers of Marek and Harikrishnan Viswanathar. Both should do what i asked for.




回答4:


There is one solution that I figured out now.

You can set a boolean isPending when ajax request is send you can set this value to true

After ajax callback is called(success or error) you can set isPending to false;

Moreover, you can have a string variable searchContent and update this variable when text is changed. So when Ajax Call is not pending and searchContent has content you can send another ajax call.

The best option is to use already written solution for example: http://jqueryui.com/autocomplete/ it is very easy and it works very well it has even already built in caching system.



来源:https://stackoverflow.com/questions/16810339/how-to-cancel-a-php-process-when-ajax-call-is-cancelled

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!