EasyAutocomplete - example

JQuery autocomplete plugin.

This example shows how you can use EasyAutocomplete with ajax POST requests.




Javascript:

var options = {

  url: function(phrase) {
    return "api/countrySearch.php";
  },

  getValue: function(element) {
    return element.name;
  },

  ajaxSettings: {
    dataType: "json",
    method: "POST",
    data: {
      dataType: "json"
    }
  },

  preparePostData: function(data) {
    data.phrase = $("#example-ajax-post").val();
    return data;
  },

  requestDelay: 400
};

$("#example-ajax-post").easyAutocomplete(options);

HTML:

<input id="example-ajax-post"/>

Search response

[
  {
    "name": "AFGHANISTAN"
  },
  {
    "name": "ALBANIA"
  },
  {
    "name": "ALGERIA"
  },
  {
    "name": "AMERICAN SAMOA"
  },
  {
    "name": "ANDORRA"
  },
  ...
]


EasyAutocomplete uses jquery $.ajax function for performing an asynchronous HTTP (ajax) request. If you want to use POST method to retrieve autocomplete items from remote source, you need to set object ajaxSettings property (more about it).

ajaxSettings: { dataType: "json", method: "POST", data: { dataType: "json" } }

  • dataType - the type of data that you're expecting back from the server
  • method - the HTTP method to use for the request
  • data - data to be sent to the server

To add some dynamic data to POST request, you need to use function preparePostData. This is function is invoked just before sending ajax request, so data is dynamically assigned to request. In this example you can see, that input field value is added to POST data.

preparePostData: function(data) { data.phrase = $("#example-ajax-post").val(); return data; }