How to use Typeahead.js with async ajax data source

Twitter development has provided an open source javacript jQuery plugin Typeahead.js to build typeahead UI elements for your applications. It is a great library that you can use as a starting point to development typeahead components that are targeted for your custom requirements. The library's example web page starting samples to learn some basic usage for typical use cases of the applications.

Unfortunately, there is no documentation available for this library. Your best bet is to google with specific set of questions that pertain to your use case. The library's source code at Github has a sample as well that you can use to learn more about the library. One of the common use cases that I have come across is using asynchronous AJAX data source to provide the suggestions for typeahead. When I searched around for this use cases, I found lot different answers with different type of solutions. So I decided to do some digging in the source code of this library to figure out the functionality available in the library that will allow me to integrate an asynchronous data source for typeahead. This post will provide a sample implementation that I developed for my own application.

    <script type="text/javascript">
    let apiUrl = "/company/names";
    $("#company-name .companyname").typeahead({
        hint:true,
        highlight:true,
        minLength:2
    }, {
        async:true,
        source: function (data,process, <strong>processAsync</strong>) {
            try {
                let requestData = {query:data};
                $.ajax({
                    url: apiUrl,
                    type: "POST",
                    cache: false,
                    context: this,
                    data: JSON.stringify(requestData),
                    contentType: "application/json; charset=utf-8",
                    clientCallTime: new Date(),
                    success: function (data, textStatus, jqXhr) {
                        processAsync(data);
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        console.log(throwError);
                    }
                });
            }
            catch (err) {
                console.log(err);
            }
        },
        templates: {
            header: '<strong>Suggestions</strong>',
            footer: function (data) {
                return `<hr/><strong>Searched for:${data.query}</strong>`;
            }
        }
    });

I will explain functionality of the above code that is key to the integration of asynchronous AJAX data source for typeahead. First, source property has been assigned a function. After user has enetered a minimum of 2 characters in the input field, typeahead will call this function to get list of suggestions. This function has 3 parameters.

  • data:This parameter contains the query text the user has entered in the input field.
  • process:This is the callback function that you can use to process the list of suggestions.
  • processAsync:This is the call function that you can use to process the list of suggestions. Notice that I have appended async to the name. This indicates that if your using asynchronous data source, then use this async function and not the callback function provided as second function parameter.

The key is to use the third function parameter processAsync to process the results returned by AJAX request. If you will try to use process callback function, the library will not display any suggestions returned by AJAX request. Inside the library's code, it processes the data differently for synchronous and asynchronous callback. When you call process callback, the code return immediately without rendering the suggestions.

I had to dig through the library's source code to find out how it process's the data returned. I hope it helps in answering the questions related to how to use asynchronous AJAX data source for typeahead. If you have any additional questions or need some help, feel free to leave a comment.

Search

Social

Weather

19.5 °C / 67.1 °F

weather conditions Clouds

Monthly Posts

Blog Tags