Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

lewanay's avatar

Getting all data from database through ajax

Hello everyone .... I am trying to get data from database... My code is working because in the console i can see my my data but in the table i only recieve the last added data to the data base .. Below is my code

//Controller public function index() { $classes = StudentsClass::pluck('class_name', 'id')->all(); $students = Student::all(); return view('admin.students.attendance.index', compact( 'classes', 'students')); }

public function mytableAjax($id)
{
    $students = Student::where('students_class_id', $id)->get();
    return json_encode($students);
}

//View

        <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></td>
                <td></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) {

                        $.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"]').html(markup);
                        });
                    }

                });

            }

        });

    });

//Routes

Route::get('myform/ajax/{id}',array('as'=>'myform.ajax','uses'=>'AttendanceController@mytableAjax'));

Route::resource('/students/attendance', 'AttendanceController', ['names'=>[

'index'=>'admin.students.attendance.index',

]]);

0 likes
23 replies
jlrdw's avatar

This was just done yesterday, you left out append:

$('table[id="studentsData"]').append(markup);
lewanay's avatar

@JLRDW - Yes when i do append then i get the old data repeated again and again

jlrdw's avatar

This:

public function mytableAjax($id)
{
    $students = Student::where('students_class_id', $id)->get();
    return json_encode($students);
}

Call it without ajax to see if you are getting correct results:

public function mytableAjax($id)
{
    $id = 1; // or $id = '1';  // for example use a real id   
    $students = Student::where('students_class_id', $id)->get();
    dd($students);
    return json_encode($students);
}

If you are not getting the expected results, then troubleshoot that.

lewanay's avatar

@JLRDW - By doing this i am getting first added data at the backend

jlrdw's avatar

Are you saying it's not the correct results.

lewanay's avatar

@JLRDW - Getting this data really make me tired . I used too approaches. One is this where i am getting this result and another approach give me the correct data but the problem is everytime i get my layout get duplicated.. Pls help me out

lewanay's avatar

@JLRDW - It is the correct result but how i can bring it now to the frontend because when i do that then it give me last added result and with append it give me old data repeated again and again

jlrdw's avatar

Did you remember to clear the data before looping:

$('table[id="studentsData"] > tbody').html('');
lewanay's avatar

@JLRDW - Yes i am getting the same result after doing that too.. The last added result just

jlrdw's avatar

You said:

and another approach give me the correct data but the problem is everytime i get my layout get duplicated

Clearing the data first with the "another approach" shoult wotk.

Try clearing data. send nothing to it except a word.

<p>test</p>

and see if it works, don't loop. Get it working first with real simple stuff.

lewanay's avatar

@JLRDW - Ok but let me explain you clear my another approach... And below is my code pls take a deep review of it... In this approach i am getting the correct data and also that data is showing in the table but whenever the data shows in the data then also destroys my layout..When i open the inspect element then i can see there that inside my table the whole layout is duplicated again.. Let me show you the code

//My routes

Route::resource('/students/attendance', 'AttendanceController', ['names'=>[

'index'=>'admin.students.attendance.index',

]]);

//My controller

public function index(Request $request) { $class_id = $request->class_id; $students = DB::table('students')->join('students_classes', 'students_classes.id','students.students_class_id')->where('students.students_class_id', $class_id)->get(); return view('admin.students.attendance.index', compact( 'students')); }

//My view

<select>
    @foreach(App\StudentsClass::all() as $class)

            <option id="class{{$class->id}}" value="{{$class->id}}">{{$class->class_name}}</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 () {
            @foreach(App\StudentsClass::all() as $class)
            $("#class{{$class->id}}").click(function () {
                var classes = $("#class{{$class->id}}").val();
                $.ajax({

                    url: '{{url('/students/attendance')}}',
                    type: "GET",
                    dataType: "html",
                    data: 'class_id=' + classes,

                    success: function (response) {
                        // console.log(response);
                        $('table[id=studentsData]').html(response);
                    }

                });
            });
            @endforeach
    });
jlrdw's avatar

Have you thought about using https://github.com/yajra/laravel-datatables

It may help you out.

Otherwise, start small and get it working with just one word first like I said above.

And see if you are clearing the data before the loop, sounds like you are clearing it at the wrong place.

Try

$('#studentsData tbody').empty();
lewanay's avatar

@JLRDW - I looked at that but that does not really help me because it does not have any dropdown

jlrdw's avatar

All I can suggest is do your code in small segments, dd at places, alert at places to see what's going on.

You need to, not worry about the whole table at first. Instead, like I said practice clearing out the area, then using jquery write just one thing there.

Use a division, and just empty out the whole division. Later put the table data in the division.

Small steps.

lewanay's avatar

@JLRDW - Can you give me an example pls. I can't get your this point

jlrdw's avatar

Have a division, in division have table. Just clear all from the division. That way you just create the table inside the div each time.

Give the division an id.

1 like
Cronix's avatar
Cronix
Best Answer
Level 67
var markup = '';

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

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

You're overwriting markup and overwriting that table on each loop. So it only shows the last value of the loop (actually it's showing all one at a time but faster than you can see it). Build up the text within the loop, and then add the built up text outside of the loop.

This is talking about your very first post, and explains

My code is working because in the console i can see my my data but in the table i only recieve the last added data to the data base

1 like
lewanay's avatar

@CRONIX - Can I insert a big layout for table into javascript because i want something more in my table not only values

Cronix's avatar

I'm not sure what you mean exactly. One thing I'd do though is put an id on the table <tbody>, and then target that in the success method instead of the whole table. That way your <thead> will stay the same since you're not deleting it. Only replace the table body contents.

<tbody id="tableBody">
$('#tableBody').html(markup);
lewanay's avatar

@CRONIX - Thats what i did while ago but same result so i just write the whole table layout in the javascript where i am getting the data through ajax but now i cannot understand that how i will bring this table data from javascript to my controller. Can you explain it please ? I also post this question you can check that too please and code my also

Please or to participate in this conversation.