Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate select list from JSON

Tags:

json

jquery

php

I've been looking around for a solution to what appears to be a simple problem, but am unable to find the solution...any guidance would be appreciated.

I am attempting to build a select box using JSON object retrieved from a PHP script. The PHP script (versions.php) is running a query against a database table; code is as follows:

$posts = array();
if(mssql_num_rows($result)) {
  while($post = mssql_fetch_assoc($result)) {
    $posts[] = $post;
  }
}
header('Content-type: application/json');
echo json_encode($posts);

...and returns the following json structure:

[{"version":"3.3.0"},{"version":"1.5.0"}]

The PHP file is being called from a central JS file, which is structured as follows:

jQuery(function($){
    $.getJSON('versions.php', function(data) {
        var select = $('#release-list');
        $.each(data, function(key, val){
            var option = $('<option/>');
            option.attr('value', val)
                  .html(data)
                  .appendTo(select);
        });
    });
});

Looking at firebug, I see lists of objects, but not the values in the array. I guess this is related to the code in the javascript file above - just not sure how to access the values from the json object.

Thanks in advance.

like image 700
user778444 Avatar asked Feb 15 '26 21:02

user778444


1 Answers

You're almost there. Based on your JSON structure, It should look something like this:

jQuery(function($){
    $.getJSON('versions.php', function(data) {
        var select = $('#release-list');
        $.each(data, function(key, val){
            $('<option/>').attr('value', val.version)
                  .html('version ' + val.version)
                  .appendTo(select);
        });
    });
});
like image 122
Stephen Avatar answered Feb 18 '26 13:02

Stephen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!