Code_Ed_Student
Code_Ed_Student

Reputation: 1190

Populating the select input field with mysql data

I have created a main drop down list and with jquery I can choose the number of drop down menus to display. Done very simply by a for loop. The main dropdown list to choose how many drop downs to display is statically populated and I am trying to dynamically populate the drop downs being displayed with data in mysql database. In the php side I am using a while loop to populate each select box. I am not getting any results being displayed. SITE

<script type="text/javascript">
    $(document).ready(function () {

    $('select').change(function() {
    var option = $(this).val();
    showFields(option);
    return false;
        });


        function showFields(option){ 

            var content = '';
            for (var i = 1; i <= option; i++){
                content += '<div id="course_'+i+'"><label>Course # '+i+'</label><br /><label>Course Name:</label> <select id="coursename_'+i+'"><option value="">--- Select ---</option>"'
                        <?php



                           $mysqli = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
                           if (mysqli_connect_errno()) {
                                printf("Connect failed: %s\n", mysqli_connect_error());
                                exit();
                            } 
                            $course_query = "SELECT course_id, course_name FROM course ";
                                    if($result = mysqli_query($mysqli, $course_query)) {
                                        while ($idresult = mysqli_fetch_row($result))
                                        {
                                            $course_id = $idresult[0];
                                            $course_name = $idresult[1];
                                            echo'<option value="' . $course_id . '">' . $course_name . '</option>';
                                        }
                                    }
                        ?>
                '"';                   

                content += '</select><br /><div><br />';

            }
            $('#course_catalog').html(content);

        }
    });
</script>

Upvotes: 0

Views: 323

Answers (1)

scrowler
scrowler

Reputation: 24406

You need to echo a javascript line to start with, instead of echoing directly...

echo 'content += \'<option value="' . $course_id . '">' . $course_name . '</option>\';';

Upvotes: 1

Related Questions