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

The issue of Angular 6 view failing to display accurate data upon page load

In my Angular 6 application, I've implemented a login feature using Firebase's Google login. The interface includes a button labeled Login when the user is logged out, and changes to Logout with the current email address displayed when the user i ...

Launching the webpage with Next.js version 13

Hey there! I'm currently working on implementing a loading screen for my website to enhance the user experience. Since it's quite a large site, I believe a loading screen would be beneficial. However, I'm having trouble getting it to work on ...

Trying to toggle between two Angular components within the app component using a pair of buttons

Currently, I am developing an application that requires two buttons to display different nested apps. Unfortunately, I am unable to use angular routing for this particular design. These two buttons will be placed within the app.component. When Button A i ...

What causes the image to not appear at the center bottom of the page when using IE for loading?

Why does the loading image not appear at the center bottom of the page in IE? This function loads content when the page is loaded and also loads content when scrolled to the bottom. When you load the page index.php, you will see the loading image at the ...

The div is not displaying the conditional styling as expected

I need help with mapping an array of cards wrapped in a div. I want the first, second, second-to-last, and last divs to go on a new line or take up the entire row. My project is in Vue3 and I'm using the PrimeVue component library. <div class=" ...

Error message: "An issue occurred: Unable to access undefined properties (specifically, borderRadius) in MUI react."

I recently created a navigation bar with an integrated search bar component. The styling for my search component was done using MUI styled from @emotion/styled in MUI library, where I applied a borderRadius: theme.shape.borderRadius. However, I encountere ...

Adding npm packages to your Vue.js application

My Vue app is structured like this (auto created by vue init webpack myProject): index.html components/ -main.js -App.vue I am trying to include npm packages, such as https://github.com/ACollectionOfAtoms/atomic-bohr-model. Following the instructions, I ...

JavaScript - Attempting to Add Objects to Array Unsuccessful

After seeing this question raised multiple times, I am determined to find a solution. In my current project, I am tasked with displaying a list of orders and implementing a filter by date functionality. However, I keep encountering an error when trying to ...

Can an AJAX request continue running even after the user has moved to a different page within the website?

Currently on my website, users are able to submit a form using ajax. The response, indicating whether the form was successfully submitted or if there was an issue, is displayed in an alert message. However, due to the asynchronous nature of this process, i ...

Extracting information from Postgres and converting it to JSON format while dynamically updating the column names

Is there a way to selectively import specific columns from a table in json and alter their names during the process? For example: MyTable (id, column1, column2, columns3) I aim to transform them into json format as follows: MyTable: {column11, column2, ...

Tips on effectively utilizing dynamic data with Google Charts

I am working on creating a dynamic chart using Google Charts with multiple CSV files. I want to display a different chart depending on the selection made by the user. The first file loads successfully and displays a chart, but the $("#selection").change(.. ...

Ways to send a specific row to an AJAX function within a Codeigniter view

Having just started using codeigniter, I am looking to transfer a row returned from the controller via the model to an ajax function within a view. The current code snippet below demonstrates how I am able to retrieve data from the model in the controlle ...

Displaying a certain div when clicked within a loop using Vue.js and Laravel

I am currently facing an issue with displaying a hidden div upon click. The problem arises when using a loop to dynamically generate all the divs. Whenever I click the button, it shows all the divs instead of just one specific div on each click. I attempte ...

Unexpected Issue Encountered in JQuery Integration

I recently added jQuery to my HTML file: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> After that, I included a link to my JavaScript file: <script src="public/javascripts/new_javascript.js" type ...

How can I effortlessly convert a freemarker object into JSON format?

Is there a built-in feature in freemarker that allows me to easily convert my data structure into JSON notation for output? Something akin to Javascript's JSON.stringify, perhaps through a simple method like object?json? ...

Real-time communication using Ajax technology in web-based instant messaging applications

I'm curious: Is it feasible to implement a basic Ajax instant messaging system for a popular social network with thousands of users? I am new to this, so I am just curious. What if we checked for new messages every two or three seconds? Revised: Can ...

I need to fetch data from mongoDB by allowing the user to input a name into a search field, and then retrieve all documents that correspond to that search term

I am currently able to query the database by finding a specific key:value pair in the documents. However, I would like to enhance this functionality by allowing users to input their own search criteria as an argument in the function. Right now, I have hard ...

jQuery: Track mouse movement with a delay

I'm looking to create a div that follows cursor movement with a slight delay, similar to the effect seen on this website: In the example link provided, you can observe that the 'follower' has a brief delay in its animation. I attempted to ...

Verifying email availability using VB.NET WebMethod, JSON, and CustomValidator

I have been researching this issue extensively, both on this site and others, but have yet to find a solution that works for me. My goal is to validate whether a given email address is already in use in a database during the registration process. On my Re ...

Uploading files with Angular and NodeJS

I am attempting to achieve the following: When a client submits a form, they include their CV AngularJS sends all the form data (including CV) to the Node server Node then saves the CV on the server However, I am encountering difficulties with this proc ...