Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery UI Autocomplete - catch HTTP errors from source

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!

like image 760
papaiatis Avatar asked Jul 18 '12 09:07

papaiatis


1 Answers

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'
            });
        }
    });​
like image 110
Steven Avatar answered Nov 07 '22 03:11

Steven