Exploring CakePHP 3's capabilities with JSON response: Enhancing response data format by connecting with related tables

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">&times;</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).

Answer №1

Why are you choosing to request JS via AJAX and then running another query to fetch JSON, only to display it in a modal? This process seems unnecessary and quite unusual. Unless I am misunderstanding the situation.

  1. You can simplify this by calling the action and directly returning the entire HTML content for the modal so that CakePHP can render the data on the server side. This would require just one AJAX call.
  2. Alternatively, you could have a template like
    <script type="html/template" id="model-template">content here</script>
    . Upon clicking, make an AJAX call to retrieve JSON, replace the placeholders like {{somevar}} in your template with the JSON data, and finally place the result in your modal. Again, this approach involves just one AJAX call. You may consider using Mustache.js for easy template parsing as it is lightweight.

Personally, I find working with JSON responses and filling templates to be more efficient.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best method to determine the current scroll position using JavaScript?

Presently, I am focusing on implementing scroll to top button functionality. The button appears when the content is scrolled to the bottom. My goal is to store the last position when the scroll to top button is clicked so that the user can return to that ...

Please elaborate on the appropriate application of angularjs Directives in this specific scenario

From my experience with Angular, I've learned that directives are used for manipulating the DOM while controllers are more about controlling functionality. I've been struggling to convert a small wizard into generic directives, aiming for reusab ...

Data is not being refreshed by Ajax

In my forum, users are only allowed to edit and delete their own comments. I have set up an "edit" button that opens a modal when clicked, giving the user access to the data they submitted before. I've written an ajax function to target these fields a ...

What's the best way to organize a list while implementing List Rendering in VueJS?

Currently, I am working on List Rendering in Vue2. The list is rendering correctly, but it appears ordered based on the data arrangement in the array. For better organization, I need to sort each item alphabetically by title. However, I am facing difficult ...

Exploring the integration of custom filters in AngularJS for enhanced visualization with Fusion Charts

I've encountered an AngularJS issue with Fusion Charts. I'm struggling to arrange the data according to one of the values in JSON data. The Fusion Chart currently displays mixed-up data, but I aim to filter it based on specific criteria as depict ...

Error: The function "execute" has not been declared

Hey there! I've created a Discord bot that is meant to check the status of a Minecraft server, but I'm encountering an issue with the embed. It's showing this error: UnhandledPromiseRejectionWarning: ReferenceError: execute is not defined. ...

What are the steps to convert JSON into CSV format?

I am working on a code that looks like this $username = "username" $password = "password" $base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username, $password))) $response = Invoke-RestMethod -Headers @{Authoriz ...

Change the background color according to the user's input text

I want to create a text box where users can input color keywords like blue, lime, or black. When they click submit, I want the background color of the page to change accordingly. This is what I have so far: <label for="color">Color: </label> ...

What is the process of transforming a list of arrays, which is in JSON format, into Dart?

Having trouble with the JSON_ANNOTATION feature when dealing with a json that contains nested arrays. Uncertain about how to convert the paths in the array into a single Paths object. Maybe something like this, but it doesn't seem to handle multiple ...

React Container failing to Re-Render despite Redux State Change

I have encountered an issue while working on Redux and React. I am developing a book list where clicking on a book will display its details. Upon selecting a book, the action is properly handled and the state is updated as expected. // reducer_active_boo ...

In Laravel Controller, the Concatenation assignment works perfectly fine without any issues, even when adding a variable of eloquent relation to the Ajax query. The

Encountering a 500 error when trying to add a variable to the concatenation assignment '$output' in an Ajax query that is functioning correctly. Currently working on an application utilizing Laravel to showcase resources linked with selected top ...

Decoding JSON Array Data Sent via Ajax请求

Could someone provide guidance on parsing this Ajax response in jQuery? {"d":{"__type":"ListUsers+returnData","Type":"Success","Message":"User Added successfully."}} I am utilizing identical return types for various return data scenarios. ...

React - method for transmitting dynamically generated styles to a div element

As a newcomer to the world of React, I keep encountering an unexpected token error related to the ":". Can someone please assist me with understanding the correct syntax for including multiple styles within the Box component provided below? Additionally, h ...

Experiencing delays with AngularJS $http responses

I have this code snippet which is causing an issue: $http.get('/api/users'). success(function(data) { $scope.authors = data; }). error(function() { console.log('API error - configuration.') }); Further down in the code: for ( ...

Issue with Axios Get method: Data not displaying in table

Can someone assist me with displaying JSON data on my website? I am using an API with a security token, and everything seems to be working fine until I try to display the JSON data on my page. I can see the data in my console, but not on the actual page. ...

"Maximize User Experience with DropDownExtender in Ajax

I am trying to implement an Ajax Dropdownextender on my website, but it's not working properly. This is the code I have: <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:Scr ...

What is the best way to iterate through all JSON data and dynamically add it to my HTML?

I am looking to inject the Json data into my file.php in a structured manner, where each group is enclosed within its own div with consistent styling. It seems like my current approach may not be the most efficient. Any recommendations for better solution ...

Interested in transferring an additional column value to the $scope.seriesSelected variable?

I've been delving into Timeline charts using the angularjs google chart API and have come across an interesting limitation. It seems that only 4 columns are allowed, with the extra column designated for tooltips. However, I have a specific requirement ...

Ensure that the array in Jest does not have any falsy values present

Attempting to utilize Jest for a unit test to ensure the absence of falsy values in my array named values. Unfortunately, the initial approach is not effective; the test actually passes: const badValues = ['', null, undefined, false, {}, []]; e ...

Is the rise of web sockets rendering ajax/CORS outdated?

Do you think that web sockets will render ajax unnecessary in all web browsers? If I could utilize web sockets to retrieve and update data instantly, would there still be a need for ajax? Even if I only use ajax to fetch initial data upon application star ...