I'm making a live search using Laravel, VueJs and axios, so every time the user types a new word, the previous request will be cancelled. My problem is that even when I cancel the previous request using the cancel token (https://github.com/axios/axios#cancellation), the php script is still running.
QUESTION: How can i stop the php script if the axios request has been cancelled?
my Vuejs code
fetchData(query) {
if(cancel != undefined)
cancel(); // cancel the previous request
axios.get("http://sample-link", {
cancelToken: new CancelToken(function executor(c) {
cancel = c;
}),
params: {
query : query
}
}).then(response => {
console.log(response);
}).catch(error => {console.log(error.message)})
}
...
my php code
class SearchController extends Controller {
public function Search(Request $request)
{
$query = $request->input('query');
$accounts = Accounts::search($query, null, true, true)->get();
return response()->json($accounts);
}
...
}
I don't know exactly how the Axios cancellation works, but if the client disconnects the HTTP session (as it should) you could try using the ignore_user_abort
setting.
public function Search(Request $request)
{
ignore_user_abort(false);
$query = $request->input('query');
$accounts = Accounts::search($query, null, true, true)->get();
return response()->json($accounts);
}
Other useful functions could be:
connection_status
: Check the current status of the connection
connection_aborted
: Check if the connection has been canceled
I just want to add that your function does not seem very intensive, so I'm not sure how useful such a check is. As Tauqeer suggested in the comment, the usual approach in those situations is to apply a debounce to your javascript search function, in order to only fire the request when the user finished typing.
An example using lodash:
const search = (query) => {
.. your axios request ...
}
const fetchData = _.debounce(search, 300)
Now you can just call fetchData(query)
whenever the user types something and it will only send a request when the user stops typing for 300 milliseconds
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With