lewanay
5 months ago

Referring the json data to html template | Laravel

Posted 5 months ago by lewanay

Hello everyone I m getting data from data base through ajax in the form of json... Now i can display it but for that i have some random html code inside my ajax code and what i want is to refer this ajax to the above my actual table and display it there ... Is it possible or any alternative way here ?? Below is my code

//My code

<select name="students_class_id" class="form-control" style="width:350px">

        <option value="">--- Select State ---</option>

        @foreach ($classes as $key => $value)

            <option value="{{ $key }}">{{ $value }}</option>

        @endforeach

    </select>

    <table id="studentsData" class="table table-striped table-bordered table-list-search">
        <thead>
            <tr>
                <th>#</th>
                <th>Student ID</th>
                <th>Student Name</th>
                <th>Attendance</th>
            </tr>
        </thead>
            @foreach($students as $student)
        <tbody>
            <tr>
                <th>{{$student->id}}</th>
                <td>{{$student->student_id}}</td>
                <td>{{$student->first_name}} {{$student->last_name}}</td>
                <td>
                    <div class="form-group">
                        <select class="form-control" id="gender">
                            <option>Present</option>
                            <option>Absent</option>
                            <option>Leave</option>
                        </select>
                    </div>
                </td>
            </tr>
        </tbody>
            @endforeach
    </table>
    <a class="fas fa-folder-open btn btn-success float-right mb-4 mr-2"> Save</a>
</div>

@stop

@section('script')

<script>

    $(document).ready(function() {

        $('select[name="students_class_id"]').on('change', function() {

            var classID = $(this).val();

            if(classID) {

                $.ajax({

                    url: '/myform/ajax/'+classID,

                    type: "GET",

                    dataType: "json",


                    success:function(data) {

                        // $('#studentsData').html(response);

                        $('table[id="studentsData"]').empty();

                        $.each(data, function(key, value) {
                            var markup = '<tr> <td>' + value.id + '</td> <td>' + value.student_id + '</td> <td>' + value.first_name+ ' '  + value.last_name + '</td> <tr>';


                            $('table[id="studentsData"]').append(markup);
                        });
                    }

                });

            }

        });

    });

</script>

@stop

Please sign in or create an account to participate in this conversation.