9

I'm using the jQuery UI Autocomplete plugin to create a quick search bar that will populate a dropdown list of matched elements.

Everything works fine but I would like to prepare my search plugin to handle HTTP errors as well that comes from the ajax call.

I didn't find a way to handle this. I read through the documentation: http://jqueryui.com/demos/autocomplete/ but it seems there is no such event or callback called 'error' that could be used for this scenario.

Want I would like to achieve is an alert box that tells the user there was an error on the server side.

Would someone give me an example of this?

Thanks!

papaiatis
  • 4,231
  • 4
  • 26
  • 38

1 Answers1

15

From the http://jqueryui.com/demos/autocomplete/ you can use the source as a function which takes two parameters, request and response. So one possible way to handle http errors would be to catch them using a jQuery ajax call as follows:

    $( "#autocomplete" ).autocomplete({
        minLength: 2,
        source: function( request, response ) {
            $.ajax({
                url: "query.php",
                data: { query: request.term},
                success: function(data){
                    response(data);
                },
                error: function(jqXHR, textStatus, errorThrown){
                    alert("error handler!");                        
                },
              dataType: 'json'
            });
        }
    });​
Steven
  • 575
  • 7
  • 13
  • 3
    Might want to add `$("#autocomplete").removeClass("ui-autocomplete-loading");` to the error handler to remove the spinner. – Leonid Nov 29 '13 at 23:01