Filling a select drop-down with ajax data using jQuery
In user interfaces, it’s sometimes the case, that you need to have dropdowns with content dynamically loaded from a database, and sure you can query the database and place the content in the HTML-source as regular markup, but you can also write a few lines of jQuery powered javascript, and provide the data from an ajax-source.
Here’s how to do it.
First make the drop-down and as the single option make a “loading” message - just to let the user know something is happening.
-- loading –
Next make a few lines of javascript, which runs once the page is ready, and let that initiate the json request (and fill out the drop down with the require values).
<script type="text/javascript">
$(document).ready(function() {
$.getJSON("select_ajax.php",{}, function(data){
var options = '<option value="">-- select please --</option>';
for (var i = 0; i < data.length; i++) {
options += '<option value="' + data[i].value + '">' + data[i].label + '</option>';
}
$("select#dropdown").html(options);
})
});
</script>
For convenience there’s a simple example available here. The example uses a static array as source, and in all practical uses this would probably be replaced by a database query.