Bootstrap Autocomplete with Dynamic Data Load using PHP Ajax

In this tutorial, we are going to see how to load data dynamically for an autocomplete suggestion list, Bootstrap Typeahead input field. I use jQuery AJAX to call the PHP MySQL script to read the data from the database and autocomplete dynamically. The loaded data will be returned to the source of the Typeahead script to list the autocomplete suggestions.

In a previous tutorial, we have implemented the Bootstrap autocomplete with local array data. In this example, it stores countries in a database table instead of a Javascript array. The source of the typeahead function is read and supplied from the database by using jQuery AJAX. I used AJAX to execute PHP script by passing the Typeahead field input as the query parameter to process the SELECT to get data for the autocomplete suggestion.

jQuery AJAX Callback to Supply Typeahead Source

The following jQuery script is used to initialize the Bootstrap Typeahead function to implement autocomplete for an input field. While typing data to the input field, the value is sent to the PHP script as the query parameter using jQuery AJAX POST method. This method received the database response in a JSON format and used as the source for showing autocomplete suggestions.

Dynamic Autocomplete using Database

The following PHP script receives the Typeahead input as the SELECT query parameter. This will be bound to the query statement to get the related country name that starts with the query string. This data will be encoded in JSON format and return to the Typehead source attribute.