heisenberg
heisenberg

Reputation: 1954

Ajax array won't populate on drop down select

As soon as selected value from dropdown1 is changed, I need to populate the corresponding data for dropdown1's selected value. The populated data must be appended to dropdown2.

I checked related answers and questions about this and tried almost every possible solution but I still can't get it to work.

html

<body>
<select id="dropdown1" class='form-control-static'>
    <option value="value1">Value 1</option>
    <option value="value2">Value 2</option>
</select>

<select id="dropdown2" class='form-control-static'>
</select>

<script src="js/jquery.js"></script>
<script src="js/externalJavascript.js"></script>
</body>

externalJavascript

$('select[name=dropdown1]').change(function (e) {
        var selected = $('select[name=dropdown1]').val() 
        alert(selected);

        $.ajax({
            type: 'POST',
            data: { name: selected },
            url: 'dbaccess.php',
            datatype: 'json',
            success: function(data) {
                alert(data);
                var $select = $('#dropdown2');
                $.each(data, function(key, value) {
                    $select.append('<option value=' + key + '>' + value.name + '</option>');
                });
            }
        });
    });

dbaccess.php

<?php
$name = $_POST['name'];
$name_id = getIdByName($name);

$names_arr = array();
$names_arr = getNamesByNameId($name_id);
//var_dump($names_arr);
echo json_encode($names_arr);
?>

The message alert box returns correct data as shown in SQL Editor alert(data) shows returned data from database as

[{"name":"My Name 1"},{"name":"My Name 2"},{"name":"My Name 3"}]

But it just won't append to the dropdown2 select no matter what I do. I don't see any problem with the ajax.

Any thoughts or ideas? I'll appreciate any help or suggestion.

Thank you.

Upvotes: 0

Views: 59

Answers (1)

vijay
vijay

Reputation: 729

Your whole code is perfect just missing one line.

Just add JSON.parse function in ajax success call.

success: function(data) {
                data = JSON.parse(data);
                .........
            }

Upvotes: 1

Related Questions