Reputation: 3523
I am trying to get the response's HTTP status code from a jQuery UI Autocomplete call but I can't see any way to do so.
$( "#site_search" ).autocomplete({source: '/members/search/suggest',
select: function (event, ui) {
var search = escape(ui.item.value);
window.location = '/members/search/?q='+search;
},
response: function (event, ui) {
console.log ($(this));
console.log (ui);
console.log (event);
}
});
The web site has a login that expires after a certain period of inactivity. However, if someone starts a search at that point, the auto-suggest just kind of takes a long time. What I'd like to do is read in the status code, see the 401 and then disable the auto-complete functionality for the page load. I know how to do that part (the api has an enable/disable toggle), but I don't know how to get the status code back, even with putting the event and ui to the console.log.
Thanks, Hans
UPDATE
Here's the final version that works under the several scenarios that were causing the problems. I'm very pleased. Thanks Amurra - big help.
// SITE SEARCH
if ($('input#site_search').length)
{
$( "#site_search" ).autocomplete({
source: function(request, response)
{
$.ajax(
{
url: '/members/search/suggest',
dataType: 'json',
data: { term: request.term },
success: function(data, textStatus, jqXHR)
{
response(data);
},
error: function(jqXHR, textStatus, errorThrown)
{
if (textStatus == 'timeout')
{
$('input#site_search').autocomplete('disable');
}
// Handle errors here
},
timeout: 2000, // the SBWS login can slow things down, too
statusCode:
{
401: function ()
{
$('input#site_search').autocomplete('disable');
}
}
});
},
select: function (event, ui)
{
var search = escape(ui.item.value);
window.location = '/members/search/?q='+search;
}
});
}
Upvotes: 2
Views: 593
Reputation: 15401
You'll want to define the source option and perform the submission yourself using $.ajax. Then handle the status codes you care about using the statusCode option:
$( "#site_search" ).autocomplete({
source: function(request, response) {
$.ajax({
url: '/members/search/suggest',
dataType: "json",
data: { term: request.term },
success: function(data, textStatus, jqXHR) {
response(data);
},
error: function(jqXHR, textStatus, errorThrown) {
// Handle errors here
},
statusCode: {
401: function () {
// Disable autocomplete here
}
}
});
});,
Note: You will need jquery 1.5+ for this to work.
Upvotes: 2