A friend asked me how to populate a drop down using  ajax, so i figured what better place to explain than the Random IT Stuff blog. So here goes….

First thing you need is you asynchronous data. This may came from any source, but it typically is acquired from a database. Lets put it in a file called async.php. I’m using PHP but you can use your chosen language.

//some array returned from db
$users = array( '0'=>array('id'=>1, 'name'=>john), '1'=>array('id'=>2, 'name'=>'mary') );

//convert to json format and print
echo json_encode($users);

Ok so now we have our data, get to the javaScript. We’ll be using jQuery so make sure you have you have it included in your project.

   $.get("async.php", function(data){
   var userObj = JSON.parse(data);
    $.each(userObj, function(i, v){
   $(#myDropdownID).append('<option value="'+v['id']+'">'+v['name']+'</option>');

Jquery’s get function will call your data asynchronously, Once we have the data our anonymous function will convert the json to something a true Javascript object. We then loop through it, and assign values to our drop down list.

Happy Coding