Autocomplete with JSON data source not working

Autocomplete with JSON data source not working

Greetings experts:

I have some C# code that's generating some JSON by building up a string.  When I visit the page (http://myServer/index.aspx) from a client, the following is displayed:

[
{"label": "James Smith", "value": "12345"},
{"label": "Peter Smith", "value": "23456"},
{"label": "Sally Smith", "value": "34567"}
]

(t here are actually about 10 sets of labels/values, but they all follow this format) and examining it using Chrome's Developer Tools reports it as a series of objects.  I've put it through JSONLint and it's reported as valid JSON.

I have a test HTML page with an input text box, id="client" and the following javascript (thanks to the depths of the interweb!):

  1. $(function() {
  2. $("#client").autocomplete({
  3.    source: function (request, response) {
  4.         $.ajax({
  5.             url: "http://myServer/index.aspx",
  6.             type: "GET",
  7.             data: request,
  8.                      dataType: "JSON",
  9.                      minLength: 2,
  10.             success: function (data) {
  11.                 response($.map(data, function (el) {
  12.                     return {
  13.                         label: el.label,
  14.                         value: el.value
  15.                     };
  16.                 }));
  17.             }
  18.         });
  19.    },
  20.    select: function (event, ui) {
  21.        this.value = ui.item.label;
  22.        event.preventDefault();
  23.    }
  24. });
  25.   });

The problem I'm facing is that, when I enter anything into the input box (even something that isn't in the list of names or values), all names are presented for selection beneath the input box. As I continue typing, the list of suitable names doesn't shrink.

Before setting this up on a server with AJAX, I worked with list of data in the same format in the javascript and that worked perfectly both in terms of presenting only a subset of the names initially and the list reducing as I continued to type. The javascript was different to that I have at present.

This is so frustrating. Is it related to how we're generating the JSON or is it a problem in the javascript? My long-term goal is to pull a list of clients dynamically from a database so hard-coding the names into the javascript isn't an option.

I'm grateful for your time and suggestions.