jQuery UI Autocomplete - catch HTTP errors from source
Asked Answered
C

1

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!

Coarsegrained answered 18/7, 2012 at 9:15 Comment(0)
F
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'
            });
        }
    });​
Fourier answered 18/7, 2012 at 9:51 Comment(1)
Might want to add $("#autocomplete").removeClass("ui-autocomplete-loading"); to the error handler to remove the spinner.Barta

© 2022 - 2024 — McMap. All rights reserved.