You’re using the AJAX feature incorrectly, in a couple of ways:
- The AJAX feature isn’t meant to load an entire data set; rather, it’s meant to query the server for data that matches the user’s search term, and to fill the dropdown with those results.
- Your
success
callback (lines 7-15 in your code) is generating HTML, but that’s not what Select2 expects. Select2 expects a processResults
callback to return a JavaScript object in a specific format. The Select2 widget will take care of converting your data object into the appropriate HTML (which, by the way, is not a series of <option>
elements).
Please go back and read the Select2 AJAX documentation, which includes code samples you can follow to use it correctly.