JQueryUI Autocomplete – single value, remote datasource

August 17, 2017

This is an example of an autocomplete field which allows to enter one single value on an input box.

The list of suggested values on the pull down are retrieved from a remote script. In this example a php script.


<html>
<head>
  <meta charset="utf-8">

  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <style>
  .ui-autocomplete-loading {
    background: white url("images/ui-anim_basic_16x16.gif") right center no-repeat;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

</head>
<body>

  <div>
    <label for="item">Item: </label>
    <input id="item" name="item" value="">
  </div>

  <script>
  $(function() {

    $("#item").autocomplete({
      source: function(request, response) {
        $.ajax({
          url: "jquery_autocomplete_search.php",
          dataType: "json",
          data: {
            search_text: request.term.split(/,\s*/).pop(),
            max_rows: 12,
          },
          success: function(data) {
            response(data);
          }
        });
      },
      minLength: 2,
      select: function(event, ui) {
        console.log("Selected: " + ui.item.value + " aka " + ui.item.id);
      }
    });
  });
  </script>

</body>
</html>

The php script must return an array in json format as shown in the following code.



Code based on https://jqueryui.com/autocomplete/#remote