Home » Php » php – getting undefined where i create dynamique select option

php – getting undefined where i create dynamique select option

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have two select box, the 1st fill in with chantiers and the 2nd fill in with ouvrages these two table between them a relation belongsTo, I want when I select a chantier in 1st select the 2nd select you must fill in the ouvrages of chantier corresponds, but 2nd select it gives me undefined.

jQuery

<script type="text/javascript">
    $(document).ready(function () {
        $(document).on('change', '#chantier_id', function () {
            var chantier_id = $(this).val();
            var div = $(this).parent();
            var op = " ";
            $.ajax({
                type: 'get',
                url: "{{ route('salarie.select') }}",
                data: {
                    'id': chantier_id
                },
                success: function (data) {
                    console.log(data);
                    $("#ouvrage_id").empty();
                    $("#ouvrage_id").append("<option value='" + data.id + "'>" + data.ouvrage + "</option>");
                },
                error: function () {
                    console.log('success');
                },
            });
        });
    });
</script>

mois.blade.php

<select class="form-control" id="chantier_id">
    <option selected disabled>Select Location</option>
    @foreach($chantiers as $chantier)
    <option value="{{ $chantier->id }}">{{ $chantier->chantier}}</option>
    @endforeach
</select>
<select class="form-control" id="ouvrage_id">
    <option value="0" selected disabled>- Select -</option>
</select>

web.php

Route::get('/select','[email protected]')->name('salarie.select'); 

SalarieController.php

public function select(request $request)
{
    $data = Ouvrage::select('ouvrage', 'id')->where('chantier_id', $request->id)->take(100)->get();
    return response()->json(['option' => $data]);
}
How to&Answers: