This was just done yesterday, you left out append:
$('table[id="studentsData"]').append(markup);
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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>
@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',
]]);
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
Please or to participate in this conversation.