Unable to display all data with identical IDs in the modal

Trying to display my message thread within a modal is proving difficult. When I click the modal button, not all messages with the same reference number are being retrieved. It seems that my code is executing the query before receiving the reference number passed to the controller. Can someone assist me in resolving this issue? Here's a snippet of my code:

This is the HomeController:

   public function getAllMessage(Request $request){
 $refNumber = $request->get('refNumber');

    $messageThread = DB::TABLE('i_di_thread')
     ->SELECT('message')
     ->WHERE('refNumber', $refNumber);
     return view ('showInquiries', ['messageThread'=>$messageThread]);

}

This is the JavaScript function:

 $('#inquire_t tbody').on('click','#mensahe',function(){
           var refNumber = $(this).attr('value');

        getMessageThread(refNumber);

        function getMessageThread(refNumber){
            $.ajax({
                url: 'getMessageThread',
                type: 'GET',
                headers: {'X-CSRF-TOKEN':$('meta[name="csrf-token"]').attr('content')},
                data: 'refNumber='+refNumber,
                dataType: 'text',
                success:function(msg){
                }//each
            });
        }

And here's the blade template:

 <!-- MODAL FOR MESSAGE THREAD -->
<div id="threadmessage" class="modal fade" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h3>Message Thread</h3>
            </div>
            <div class="modal-body" style="height: 300px;" >
                <div class="row" style=" margin-left: 30px; margin-bottom: 5px; left: 20px; width: 550px; height: 200px; overflow: auto;">
                    <div>
                        @foreach ($messageThread as $thread)
                                {{$thread->message}}
                                <br>
                        @endforeach
                    </div>
                    <br>
                </div>
                <div>
                    <br>
                    <div class="col-md-2"> 
                        <b> Message: </b><br>
                    </div>
                    <div class="col-md-10"> 
                        <textarea required=" " id="messageContent" style="resize: none;" class="form-control" rows="2"></textarea>
                    </div>
                </div>
                <br>
            </div>
            <div class="modal-footer">
                <div>
                    <button type="button" id="btn-message" class="btn btn-default" data-dismiss="modal" style="background-color: #3c5fa6; color: white;"> 
                        Send <i class="fa fa-paper-plane-o ml-1"> </i>
                    </button>
                </div>
            </div>
        </div>
    </div>

Answer №1

Accessing message from the 'i_di_thread' table using Laravel's query builder:
DB::table('i_di_thread')
     ->select('message')
     ->where('refNumber', $refNumber);

This will return an instance of

Illuminate/Database/Eloquent/Builder
. Refer to the documentation here.

To execute the query as a "select" statement, add ->get(). To learn more, visit this link.

Here is the complete code snippet:

Retrieve all messages with a specific reference number and display them:
public function getAllMessage(Request $request){
    $refNumber = $request->get('refNumber');
    $messageThread = DB::table('i_di_thread')
                     ->select('message')
                     ->where('refNumber', $refNumber)
                     ->get();
    return view ('showInquiries', ['messageThread'=>$messageThread]);

}

UPDATED

If you are displaying data synchronously with Blade templates, refer to this stackoverflow answer for dynamically fetching and displaying data in a modal: Click here.

Note: To prevent errors when accessing optional properties, use the Laravel helper function optional.

For example:

<div class="row" style=" margin-left: 30px; margin-bottom: 5px; left: 20px; width: 550px; height: 200px; overflow: auto;">
                    <div>
                        @foreach ($messageThread as $thread)
                                {{optional($thread)->message}} {{-- accessing property without causing error --}}
                                <br>
                        @endforeach
                    </div>
                    <br>
                </div>

Answer №2

Here is a suggestion for you:

function fetchMessages(Request $req){
 $reference = $req->input('reference');

    $messages = DB::TABLE('i_di_thread')
     ->SELECT('message')
     ->WHERE('reference', $reference)->get();
     return view ('displayMessages', ['messages'=>$messages]);

}

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

Integrating JSON with the DOM

Currently, I am searching for a library that offers a simple method to bind JSON data to existing DOM elements that have been generated by a Rails view template. The main reason behind this requirement is that my application features in-place editing (uti ...

Is it necessary to make multiple calls following a successful AJAX request?

Here is an AJAX call I am setting up. The first step is to hit the endpoint dofirstthing.do. Once that is successful, the next step is to make another call with "param1" as the query parameter. Now, my question is - how can I make a third call with "param ...

Filtering rows in angular based on the current data's id

currData = { id: "iStyle1", status: "PENDING" }; data = [ { id: "splitStyle1", rows: [ { id: "1cUMlNRSapc5T", row: 2, sequence: 2, status: ...

Emulating a button press on the login screen

I have been attempting to utilize jQuery to simulate a button click on a login page. Interestingly, the conventional JavaScript method functions as expected: document.getElementById('loginButton').click(); However, the same action using jQuery ...

Implementing Cross-Origin Resource Sharing (CORS) in play-framework version 2.5.x: A Step-by-Step Guide

My current challenge involves retrieving JSON data by sending a request to a Restful URL from localhost within an AngularJS-1 application. The error that I encounter is as follows: http://localhost:9000/mlm/user/all Failed to load resource: the server r ...

Exploring ways to retrieve texture dimensions using Three.js

Can someone please advise me on how to retrieve the dimensions of a texture? I have set my texture using the following line of code: const texture = THREE.ImageUtils.loadTexture(src) Do I need to load the image in order to obtain its dimensions (and can ...

Executing a callback function in Swift using JavaScriptCore

Struggling to figure out how to call a Javascript Function with a callback from Swift, but it's not working as expected. Here's what I have: Javascript: global.calculateWithCb = function(temp,cb){ cb(5 * temp) } global.calculate = functi ...

Creating a React Native project without the use of TypeScript

Recently I dived into the world of React Native and decided to start a project using React Native CLI. However, I was surprised to find out that it uses TypeScript by default. Is there a way for me to create a project using React Native CLI without TypeS ...

How can I efficiently generate a table using Vue js and Element UI?

I am utilizing element io for components. However, I am facing an issue with printing using window.print(). It currently prints the entire page, but I only want to print the table section. ...

Assign a class when a path is clicked using Leaflet.js

My goal is to apply a specific class to the clicked polygon by using the following code: function addClass() { function style(feature) { return { className: "active" }; } } function onEachFeature(feature, layer) { ...

Attempting to incorporate a JavaScript script into my Java Maven project

Currently, I am incorporating an Ajax request into my Java Maven project. This project follows the MVC pattern, with the view being rendered in HTML and the model and controller being implemented in Java. My goal is to retrieve data from a data set contain ...

Using Angular $resource to store an object with arrays

Consider a scenario where we have a User $resource structured as follows: $scope.user = { name: 'John', hobbies: [1, 2, 3] } If we were to save User.save($scope.user) to the server, it would send the following parameters: name: 'John& ...

Choose the Hexagonal Surface within the Octahedral Structure in THREE.js

My current project involves working with a geodesic sphere that was initially created using THREE.OctahedronGeometry. I am looking to group the triangular faces into hexagonal faces for easier selection, but I am unsure of the best approach to solving this ...

Launching a React project using the terminal - my step-by-step process

I'm attempting to initiate a new react-app utilizing the command npx create-react-app <app name> as shown below: npx create-react-app new-app However, after downloading, it seems to be stuck. It's not progressing at all. I've even rei ...

What is the most elegant way to retrieve a new item from Firebase and read it?

My goal is to display the result of a successful read on a page, with only one attempt available before the headers are set and the page is sent. I am looking to retrieve one new value, generated after a listener was initiated so as not to pull existing da ...

How to activate an event using a Bootstrap switch in VueJS 2

Dealing with a bootstrap switch has been quite interesting. In JQuery, managing it is simple, just follow the documentation: $('input[name="my-checkbox"]').on('switchChange.bootstrapSwitch', function(event, state) { console.log( ...

Collect information from a mySQL database and store it in an array

My data table, CallTriggers, has the following attributes: cloturer = 0 or 1 created_at I am looking to retrieve all the data in the following format: $array = [ ['Month', 'Total Call', 'Close'], [&ap ...

Reading data from a Node PassThrough stream after writing has finished can be achieved by piping the stream

Is it possible to write to a Node Passthrough stream and then read the data at a later time? I am encountering an issue where my code hangs when trying to do this. Below is a simplified example in Typescript: const stream = new PassThrough(); strea ...

Having trouble targeting multiple dropdowns using jQuery

I am encountering an issue with two separate dropdowns where the hover states cannot be targeted by CSS based on the HTML markup. After attempting to solve this using jQuery, I have made some progress but one problem persists. Whenever I hover over the lin ...

monitoring the winstonjs logs and inserting additional parameters

Can an argument be injected into a log, like error, debug, or info, using the configuration of winston (createLogger)? I want to intercept the log and include an object in each log entry. ...