Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery autocomplete timeout

For some reason the ajax requests I make on the website I'm working on abort half of the time. This is resolved when I set a timeout for the ajax request like shown below.

$.ajax({
    url: "/question/why_wont_it_work",
    timeout : 1000,
    success: function(){ /*do stuff*/ }
});

Sadly the timeout fix doesn't seem to work with the jquery autocomplete. I'm using 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 the timeout option there either. Now this is pretty annoying since half of the time my request will abort and I won't get the results I want. Is there a way around this?

Thanks in advance.

like image 658
Ilians Avatar asked Dec 17 '22 02:12

Ilians


1 Answers

You can supply an arbitrary function to the source parameter. So you could manually make an AJAX request and specify the timeout option:

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 I'm with @El Ronnoco, you probably want to seriously speed up your request. 20 seconds is a long time to wait.

like image 128
Andrew Whitaker Avatar answered Jan 06 '23 19:01

Andrew Whitaker