Bineesh Varghese Bineesh Varghese - 6 months ago 33
Ajax Question

Ajax select option group not working

Categories and services are stored into two tables (category, service). I need to load all categories and services to a single select box based on staff selection.

//Jquery
$('.staff').change(function() {
var services = $('.service').empty();
$('<option value="" disabled selected hidden>--Select Service--</option>').appendTo(services);
$.get('ajax_service.php', {tutor: $(this).val()}, function(result) {
$.each(JSON.parse(result), function(index, item) {
$('<optgroup label="' + index + '">').appendTo(services);
$.each(item, function (name, value) {
$('<option value="' + name + '">' + value + '</option>').appendTo(services);
});
$('</optgroup>').appendTo(services);
});
});
});

//ajax_service.php
if(isset($_GET['staff'])) {
$staff_id = $_GET['staff'];
$sql = "SELECT c.category_id, c.category_name, s.service_id, s.service_name "
. "FROM service s "
. "INNER JOIN category c ON s.category_id = c.category_id "
. "WHERE s.staff_id = ? "
. "ORDER BY s.sort_order ASC";
$stmt = $pdo->prepare($sql);
$stmt->execute(array($staff_id));
$services = $stmt->fetchAll();
$groups = array();
foreach ($services as $service) {
$groups[$service['category_name']][$service['service_id']] = $service['service_name'];
}
echo json_encode($groups);
}


This code loads all categories and services but the option group is not works as expected
Result

Result HTML Code

<select class="service" name="ddlService" id="ddlService">
<option value="" disabled="" selected="" hidden="">--Select Service--</option>
<optgroup label="Advertising"></optgroup>
<option value="1">Adware</option>
<option value="2">Brands</option>
<option value="3">Modeling</option>
<option value="4">Sponsorships</option>
<option value="5">Press Release</option>
</select>


What's wrong with this code?. Can anyone help me track the issue? Thank you very much for your time.

Answer
//Jquery
$('.staff').change(function() {
    var services = $('.service');
    var html='';
    $('<option value="" disabled selected hidden>--Select Service--</option>').appendTo(services);
    $.get('ajax_service.php', {tutor: $(this).val()}, function(result) {

        $.each(JSON.parse(result), function(index, item) {
          html+='<optgroup label="' + index + '">';

                $.each(item, function (name, value) {
                   html+= '<option value="' + name + '">' + value +'</option>');
                });
            html+= '</optgroup>');
        });
    });
services.append(html);
});