Dropdown List from Database JSON

Populate a dropdown list from JSON returned by PHP/MySQL, read the selected value/text, and use the same pattern as the foundation for linked category/state/city lists.

Populate a Select from JSON Top ↑

$.getJSON(
    "student-data.php"
)
.done(function ( rows ) {
    const $select =
        $( "#student" ).empty();

    $( "<option>", {
        value: "",
        text: "Select a student"
    }).appendTo( $select );

    $.each(
        rows,
        function ( index, row ) {
            $( "<option>", {
                value: row.id,
                text: row.name
            }).appendTo( $select );
        }
    );
});

Read Selected Value and Text Top ↑

const value =
    $( "#student" ).val();

const text =
    $( "#student option:selected" )
        .text();

Database JSON Backend Top ↑

$stmt = $dbo->query(
    'SELECT id, name
     FROM student
     ORDER BY name'
);

echo json_encode(
    $stmt->fetchAll(
        PDO::FETCH_ASSOC
    )
);

See PDO connection and JSON formatting.

Download dropdown-list project Download listbox examples

Original Source Examples Retained for Migration Reference Top ↑

These source-page examples are retained so no learner-purpose example is silently lost. Use the modern examples above as the recommended implementation.

Original example 1

<?Php
require "config.php"; // Database Connection

$sql="select  id, name  from student "; 
$row=$dbo->prepare($sql);
$row->execute();
$result=$row->fetchAll(PDO::FETCH_ASSOC);

echo json_encode(array('data'=>$result));
?>

Original example 2

$.getJSON("student-data.php", function(return_data){

Original example 3

$.each(return_data.data, function(key,value){
$("#student").append(
"<option value=" + value.id +">"+value.name+"</option>"
);
});

Original example 4

<html>
<head>
<title>plus2net demo scripts using JQuery</title>
</head>
<script src="//ajax.googleapis.com/ajax/libs/
\jquery/1.8.1/jquery.min.js"></script>
<body>
<script>
$(document).ready(function() {
//////////////////////
$.getJSON("student-data.php", function(return_data){
$.each(return_data.data, function(key,value){
$("#student").append(
"<option value=" + value.id +">"+value.name+"</option>"
);
});
});
//////////////////////
});
</script>
<select name=student id=student>
</select>

</body>
</html>

Original example 5

$('#student').change(function(){
//var st=$('#student option:selected').text();
var st=$('#student').val();
alert(st);
});

Additional Original Learning Routes Top ↑






plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer