Hi all,
I'm using Ajax to open and close modals to display note data to users. Currently, everything works EXCEPT for when you click to display the note, as it only shows the note with id->1, regardless of which note you click in the foreach loop.
See below for code thats used to make this work. Any help would be appreciated, thanks.
Controller
public function noteDisplay(Client $client)
{
$data['notes'] = Note::where('client_id', $client->id)->get();
return view('database.clients.test.modal',$data);
}
public function getNoteDetails($note){
$note = Note::find($note);
$html = "";
if(!empty($note)){
$html = "<tr>
<td width='30%'><b>Created At:</b></td>
<td width='70%'> ".$note->created_at."</td>
</tr>
<tr>
<td width='30%'><b>Title:</b></td>
<td width='70%'> ".$note->title."</td>
</tr>
<tr>
<td width='30%'><b>Category:</b></td>
<td width='70%'> ".$note->category."</td>
</tr>
<tr>
<td width='30%'><b>Description:</b></td>
<td width='70%'> ".$note->description."</td>
</tr>";
}
$response['html'] = $html;
return response()->json($response);
View
<table class="table filter-table" id='noteTable'>
<thead>
<tr>
<th>S.no</th>
<th>Title</th>
<th>Category</th>
<th>Description</th>
<th> </th>
</tr>
</thead>
<tbody>
@php
$sno = 0;
@endphp
@foreach($notes as $note)
<tr>
<td>{{ $note->id }}</td>
<td>{{ $note->title }}</td>
<td>{{ $note->category }}</td>
<td>{{ $note->description }}</td>
<td><button class='btn btn-info viewdetails' data-id='{{ $note->id }}' >View Details</button></td>
</tr>
@endforeach
</tbody>
</table>
</div>
<!-- Modal -->
<div class="modal fade" id="noteModal" >
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Note Info</h4>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<table class="w-100" id="tblnoteinfo">
<tbody></tbody>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- Script -->
<script type='text/javascript'>
$(document).ready(function(){
$('#noteTable').on('click','.viewdetails',function(){
var note = $(this).attr('data-id');
if(note > 0){
// AJAX request
var url = "{{ route('getNoteDetails', ['note' => $note->id, 'client' => $note->client_id]) }}";
url = url.replace(':note',note);
// Empty modal data
$('#tblnoteinfo tbody').empty();
$.ajax({
url: url,
dataType: 'json',
success: function(response){
// Add note details
$('#tblnoteinfo tbody').html(response.html);
// Display Modal
$('#noteModal').modal('show');
}
});
}
});
});
</script>
Routes (web.php)
Route::get('/database/clients/{client}/notes', [App\Http\Controllers\ClientController::class, 'noteDisplay'])->name('database.clients.notes.show');
Route::get('/database/clients/{client}/notes/{note}', [App\Http\Controllers\ClientController::class, 'getNoteDetails'])->name('getNoteDetails');