<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
    <link href="http://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" rel="stylesheet" />
    <script src="http://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script>
    <title>Quick Select2 Ajax-powered Autocomplete Dropdown</title>
</head>
<body>

<p>The following autocomplete dropdown will list public GitHub repositories by quering the list with your search term.</p>
<select class="js-data-example-ajax" style="width: 300px;">
    <option value="" selected="selected">Search ...</option>
</select>

<script type="text/javascript">
    $(".js-data-example-ajax")
            .select2({
                ajax: {
                    url: "https://api.github.com/search/repositories",
                    dataType: 'json',
                    delay: 250,
                    data: function (params) {
                        return {
                            q: params.term, // search term
                            page: params.page
                        };
                    },
                    processResults: function (data, params) {
                        // parse the results into the format expected by Select2
                        // since we are using custom formatting functions we do not need to
                        // alter the remote JSON data, except to indicate that infinite
                        // scrolling can be used
                        params.page = params.page || 1;

                        // !IMPORTANT! your every item in data.items has to have an .id property - this is the actual value that Select2 uses
                        // Luckily the source data.items already have one
                        return {
                            results: data.items,
                            pagination: {
                                more: (params.page * 30) < data.total_count
                            }
                        };
                    },
                    cache: true
                },
                escapeMarkup: function (markup) {
                    return markup; // let our custom formatter work
                },
                minimumInputLength: 1,
                templateResult: function(repo) {
                    if (repo.loading) return repo.text;
                    return repo.full_name;
                },
                templateSelection: function(repo) {
                    return repo.full_name || repo.text;
                }
            });
</script>

</body>
</html>