I am working with two tables, each with their own set of attributes:
Sessions
- id
- staff_id
Staff
- id
- firstname
- lastname
When a link is clicked, it triggers a JavaScript function to open a modal. An AJAX call is then made to retrieve data in JSON format, which is used to populate the modal.
The link that initiates the JavaScript functionality looks like this:
<?= $this->Html->link(__('View'), ['action' => 'popup', $session->id], ['class' => 'view', 'data-id' => $session->id]) ?>
This action is part of a table on a CakePHP 3 View. The value for $session->id is determined based on the row of data that was clicked. The 'popup' action is an empty function in CakePHP 3 that helps facilitate the opening of the modal through JavaScript.
Here is the JavaScript code responsible for triggering the modal:
<script type="text/javascript">
$(function () {
$('.view').click(function (ev) {
ev.preventDefault();
var sessionId = $(this).attr('data-id');
$('#viewModal').modal('show');
$.ajax({
url:"localhost/project/sessions/details/"+sessionId+".json",
type:'POST',
success:function(res) {
if(res) {
document.getElementById("prstaff").innerHTML = res.staff_id;
}
}
});
});
});
</script>
Within my CakePHP 3 SessionsController, the 'details' function is used to fetch relevant data for the $session->id obtained earlier:
public function details($id = null)
{
$details = $this->Sessions->get($id);
$this->set(array(
'output' => $details,
'_serialize' => 'output',
'_jsonp' => true
));
}
This is the full markup for the modal that opens up:
<!-- Modal -->
<div class="modal fade" id="viewModal" tabindex="-1" role="dialog" aria-labelledby="viewModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h3 class="modal-title" id="viewModalLabel">Session Details</h3>
<br>
<table class="vertical table col-sm-2">
<tr>
<th>Staff Name:</th>
<td id="prstaff"></td>
</tr>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close
</button>
</div>
</div>
</div>
</div>
However, the end result currently displays:
Staff Name: 2 (or any other foreign key)
This is not very informative. I would like to make another AJAX call for the Staff table and link it to the initial AJAX call. This way, when populating the modal, meaningful data can be shown (e.g. "John Smith" instead of just displaying the foreign key value).