Untitled UI logotext
Solutions
WebsitesEcommerceMobile AppsWeb AppsProduction Support & Maintenance
Our work
Company
About usBlogPodcastContact us
Book a free consultation

How can i stop my AJAX call so I can start a new one?

Olivia Rhye

The use case for this was a search functionality that was triggered on keyup. That said, the more a user typed the ajax call would fire again and again till the search had queued so many ajax calls that the final result may or may not be the last ajax call to complete. Plus the user should essentially be told the search restarted and is not wasting more time finishing searches that were no longer relevant.

It's actually just a small addition using a variable i'm naming search_xhr. If there is is an active search happening, you can run the search_xhr.abort(); function to kill the process before it finishes. This is useful when ever you started to get something you wanted from a service that is no longer relevant based on a user interaction.

 

var search_xhr = null;

function api_search(options){
if( search_xhr != null ) {
search_xhr.abort();
search_xhr = null;
}

//visual start/restart queue can happen here

search_xhr = $.ajax({
type: "GET",
url: '[search_api_url]',
data: options,
dataType: "json",
success: function(ajaxdata){
//visual finish queue can happen here
search_xhr = null;
}
});
}

Ready to start a project?

Book a free consultation
Untitled UI logotext
Our work
About us
Blog
Careers
Submit a ticket
Agency Partnerships
Contact
© 2024 fjorge. All rights reserved.
Privacy