Populate dropdown dynamically using JSON data Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Populate dropdown dynamically using JSON data without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I am having problems displaying the names of golf courses in my dropdown menu. I have a PHP script that when ran, returns the names of the courses in my database. The problem is that when I apply this to my index.html dropdown page and display it in the browser, the content is not displaying the dropdown.

<?php


    $db_host = 'localhost';
    $db_user = 'root';
    $db_pass = '';
    $db_name = '';

    $con = mysqli_connect($db_host,$db_user,$db_pass, $db_name);
    if (!$con) {
    die('Could not connect: ' . mysqli_error($con));
    }   


    $sql = "SELECT name FROM courses";

    $result = mysqli_query($con, $sql) or die("Error: ".mysqli_error($con));;

    $courses = array();

    while ($row = mysqli_fetch_array($result))
    {
        array_push($courses, $row["name"]);
    }

    echo json_encode($courses);

?>

The above code successfully generates the data from the database

$(document).ready(function () {
    $.getJSON("getCourseDD.php", success = function(data){
        var options = "";
        for(var i=0; i< data.length; i++){
            options += '<option value ="' + data[i] + '">' + '</option>';
        }
        $("#selectCourse").append(options);
    });
});

The above code is not populating the course names into the dropdown menu.

The id of my dropdown menu is selectCourse.

<form> <select id="selectCourse" </select> </form>

Thanks for any help in advance.

Answer

Currently you are not setting text of option also, use

options += '<option value ="' + data[i] + '">' +  data[i]  + '</option>'

instead of

options += '<option value ="' + data[i] + '">' + '</option>';
We are here to answer your question about Populate dropdown dynamically using JSON data - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji