Posted by Arjun on Wednesday 6th June 2018

Populate Select2 with AJAX data based on X event

select2 ajax load dependent dropdowns

In this post, I would like to show you data populating in select 2 dropdown based on x event and it will get data from the remote server using Http protocol, the same technique you can apply for dependent dropdowns to show data based on the selection.

Populate Select2 with AJAX data example

In the following exmple we are loading data on page load and appending data to select dropdown, same technique you can apply with any avaliable javascript events like click, change ..etc.

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
      <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
   </head>
   <body>
      <div>
         <select style="width: 100%" class="selectmultiple" name="states[]" multiple="multiple">
         </select>
      </div>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
      <script>
         $(document).ready(function () {
         var apiUrl = 'https://jsonblob.com/api/category/f8be0591-a46e-11e7-86a2-d3ea1b9dd115';
         $('.selectmultiple').select2();
         $.get(apiUrl, function (items) {
            var newOptions = '';
            for (var id in items) {
                newOptions += '<option value="' + id + '">' + items[id] + '</option>';
            }
             $('.selectmultiple').select2('destroy').html(newOptions).prop("disabled", false)
               .select2();
            });
         });
      </script>
   </body>
</html>