kota srinu
kota srinu

Reputation: 49

jquery Autocomplete - not filtering

I am trying to user JQuery autocomplete function with an ajax call in it, which will return the list of Strings..when i am trying to type, it is showing all the list of strings and not filtering out based on the input..Not sure where i am going wrong..Below is my autocomplete function..

$("#domainNameId").autocomplete({
        source : function(request, response) {
            console.log("in ajax ");
            $.ajax({
                url : "getAllDomains",
                type : "GET",
                contentType : "application/json",
                data : {
                    env : $("#environment").val()
                },
                dataType : "json",
                success : function(data) {
                     response(data); // list of strings..
                },
                error : function(x, t, m) {
                    console.trace();
                    if (!(console == 'undefined')) {
                        console.log("ERROR: " + x + t + m);
                    }
                    console.log(" At the end");
                }
            });

        },
    });

appreciate the help..

Upvotes: 1

Views: 1368

Answers (2)

T J
T J

Reputation: 43166

Your backend seems to always return the entire data and not do any filtering ( The service name itself is getAllDomains). In that case there is no need to use the function form of source option to make ajax calls.

What you're doing is sending multiple AJAX requests to the server as the user types. If your backend always returns the same data, there is no point in sending multiple requests to it. You can simply fetch the data once and then initialize the autocomplete with the response as source, then the widget will do the filtering as user types.

The docs says:

A response callback, which expects a single argument: the data to suggest to the user. This data should be filtered based on the provided term.

So if your server doesn't do the filtering, don't use the function form to make AJAX requests.

do something like:

$(function() {
  // make a one-time request
  $.ajax({
    url: "getAllDomains",
    type: "GET",
    contentType: "application/json",
    dataType: "json",
    success: function(data) {
      // init the widget with response data and let it do the filtering
      $("#domainNameId").autocomplete({
        source: data
      });
    },
    error: function(x, t, m) {
      console.trace();
      if (!(console == 'undefined')) {
        console.log("ERROR: " + x + t + m);
      }
      console.log(" At the end");
    }
  });

});

Upvotes: 3

Zachary Puls
Zachary Puls

Reputation: 104

In the success callback, you will need to filter the data yourself using the request.term passed to the source function.

There is more information on the jQuery Autocomplete source here: https://api.jqueryui.com/autocomplete/#option-source.

Upvotes: 0

Related Questions