Pixabay / JavaScript-autoComplete

An extremely lightweight and powerful vanilla JavaScript completion suggester.
754 stars 186 forks source link

AJAX and Fetch API on this plug-in without using jQuery? #76

Open martinrios95 opened 5 years ago

martinrios95 commented 5 years ago

Referencing #65 and #61

I'm testing this plug-in with Vue-Resource, XHR and Fetch API. Have you got an example for this JavaScript's vanilla library without using third-party frameworks for requesting REST API's?

mohsentaleb commented 4 years ago

I've used it with a Tiny AJAX library (1KB) called NanonAJAX. Example:

var xhr;
var autoCompelete = new autoComplete({
  selector: "#searchbox",
  minChars: 2,
  cache: false,
  delay: 0,
  source: function(term, response) {
    try {
      xhr.abort();
    } catch (e) {}
    xhr = nanoajax.ajax(
      {
        url: "queryURL"
      },
      function(code, res) {
        var json = JSON.parse(res);
        if (typeof json != "undefined") {
          if (json.results) response(json.results); // my json has a `results` key
        }
      }
    );
  },
  renderItem: function(item, search) {
    // Your rendering goes here.
  }
});

P.S. The reason behind using xhr variable is that I needed to abort the request if user has a new key stroke and the AJAX call for the previous query should be aborted. This is very important when you have delay getting data from your server and avoids displaying irrelevant results for a query string.