How to fill a select box using json?

I'm trying to fill a select box in a HTML page using json and PHP, but when I click over the select box it just return a blank option. Whats is wrong?

HTML code:

Choice a problem:
<select name="notification" id="notification" class="form-control">
   <option value="00">Select...</option>
</select>

PHP code:

header('Access-Control-Allow-Origin: *');
include 'dbconfig.php';
try{
    $results = $DB_con->prepare("SELECT idproblema, tipoproblema FROM problema ORDER BY idproblema");
    $results->execute();
    $res = $results->fetchAll(PDO::FETCH_ASSOC);
    $hold = array();

    foreach($res as $reg){
$hold[] = array('idproblema' => $reg['idproblema'], 'tipoproblema' =>$reg['tipoproblema']);
    }
} 
catch (Exception $e) {
    echo "Data could not be retrieved from the database.";
    exit();
}
echo json_encode($hold);

Jquery code:

$(document).ready(function(){
jQuery.support.cors = true;
$('#notification').click(function(){
    $.ajax({
        url : 'url.php',
        type : 'GET',
        data : "json",
        crossDomain: true,
        success: function (data) {
        if (data.length > 0) {
            $.each(data, function (index, value) {
                $('#notification').append('<option value="' + value.idproblema+ '">' + value.tipoproblema + '</option>');
            });
        }
        else {
            var newOption= $('<option value=""></option>');
            $('#notification').append(newOption);
        }
    }
});
});
})

...............................................

1 answer

  • answered 2017-06-17 19:06 V. Krukov

    You need to add before echo in php .... header('Content-type: application/json'); .... As jQuery $.ajax set to accepting json data -- you return just text at the moment