JQuery autocomplete timeout
For some reason, the ajax requests I make on the website, I am working on aborting for half the time. This is resolved when I set a timeout for the ajax request as shown below.
$.ajax({
url: "/question/why_wont_it_work",
timeout : 1000,
success: function(){ /*do stuff*/ }
});
Unfortunately fixing the timeout doesn't seem to work with jquery autocomplete. I use it like this:
$( "#questionTags" ).autocomplete({
source: "/question/tags",
timeout: 1000,
select: function(event, ui) { /*do stuff*/ },
});
I checked the jQueryUI documentation on the website and didn't see a timeout there. Now this is pretty annoying since half of my request will be canceled and I won't get the results I want. Is there a way to get around this?
Thanks in advance.
source to share
You can provide an arbitrary function to a parameter source
. This way you can manually execute the AJAX request and provide the parameter timeout
:
var xhr = null; /* To prevent multiple calls from happening while one is in progress */
$("#questionTags").autocomplete({
source: function (request, response) {
if (!xhr) {
xhr = $.ajax({
url: "/question/tags",
timeout: 20000,
data: request,
dataType: "json",
success: function (data) {
xhr = null;
response(data);
},
error: function () {
response([]);
}
});
}
},
select: function(event, ui) { /*do stuff*/ },
});
But me with @El Ronnoco , you probably want to seriously speed up your request. 20 seconds is a long wait.
source to share
If source
is a string, jQuery autocomplete does the code shown below to load the data, so it doesn't set a timeout.
You can set the timeout globally using ajaxSetup like this:
$.ajaxSetup({
timeout: 20000,
});
But it will affect all your ajax requests.
Code from jquery.ui.autocomplete.js :: _initSource
self.xhr = $.ajax({
url: url,
data: request,
dataType: "json",
context: {
autocompleteRequest: ++requestIndex
},
success: function( data, status ) {
if ( this.autocompleteRequest === requestIndex ) {
response( data );
}
},
error: function() {
if ( this.autocompleteRequest === requestIndex ) {
response( [] );
}
}
});
source to share