One method to retrieve the id from the database when the button is clicked using ajax

In this particular scenario, I am working on a message thread that is inside a modal. The objective is to display a message thread for a specific individual based on their reference number. However, I am encountering an issue in passing the reference number to my controller and retrieving it back to my blade (within the message thread). Below are the relevant sections of code:

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>
    </div>
    

Javasript Function for Displaying the Message Modal

$('#inquire_t tbody').on('click','#showMsg-btn',function(){
       var flag = 6;   // Approved
       var refNumber = $(this).attr('value');
       var cur_flag = $(this).attr('name');
       var user = $("#username").html();
       console.log(refNumber);
       console.log(user);
       $('#threadmessage').modal({"backdrop":"static"});
    
       getMessage(refNumber, user);
    });//btn-message
    
    function getMessage(num, name){
        var refNumber = num;
        var username = name;
    
        $.ajax({
            url:'getAllMessage',
            type: 'GET',
            headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
            data: refNumber+'refNumber'+username+'&username',
            // dataType:'TEXT',
            success: function(data){
            }
       })
    }
    

Button to Trigger the Modal

"

Controller Logic for Retrieving Messages

public function getAllMessage(Request $request){
        $refNumber = $request->get('refNumber');
        $number = $refNumber;
        $messageThread = DB::table('i_di_thread')->select('message')->where('refNumber', '=', $number)->get();
        return view ('message', ['messageThread'=>$messageThread]);
    } 
    

Route Configuration

Route::get('showInquiries','HomeController@getAllMessage');
    Route::get('getAllMessage','HomeController@getAllMessage');
    

Answer №1

If you want to pass your data using two different methods, make sure to concatenate it properly to avoid errors:

Method 1 :

$.ajax({
        ...
        data : { 'refNumber' : refNumber, 'username' : username },
        ...
});

Method 2 :

data:'refNumber='+ refNumber + '&username='+ username

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

Issue: The variable does not appear to be getting updated

After spending the last 2 hours analyzing this JS code, I am still unable to figure out why the variable "message" is not being changed to "User already exists." The bizarre thing is that the code block labeled "Inside first if" is executed, but the "mes ...

Is the direct checkout link specifically designed for use on individual product pages?

Currently, I am working on enhancing a WooCommerce website by enabling Ajax across all pages. As part of this optimization, I have introduced a custom Direct Checkout button to the checkout form. However, there seems to be an issue with the functionality o ...

The function for fetching JSON data using AJAX is not functioning properly

Can someone help me troubleshoot why my code isn't working to retrieve a JSON file from a PHP page? Here is my PHP page: header('Content-type: application/json'); $jsonstart="{'files' : ["; $jsonend="]}"; $content="{'fir ...

Display thumbnail images in jquery-ui dropdown menu

Hello, I'm looking to display a small image (the user's thumbnail) on the jquery-ui dropdown by making an ajax call. As someone new to ajax and unfamiliar with jquery-ui, I would appreciate some guidance in the right direction. Thank you! HTML/J ...

Please enter a number using the "+" sign and a decimal point

In my input field, I have specified: <input type="number" step="0.01"> I expect all of these input values to produce the following outputs: 2.00 => 2.00 2,00 => 2.00 +2,00 => 2.00 However, when entering the value "+2.00", it fail ...

Excluding node modules when not included in tsconfig

Within my Angular project, there is a single tsconfig file that stands alone without extending any other tsconfigs or including any additional properties. Towards the end of the file, we have the following snippet: "angularCompilerOptions": { ...

Is there a way to incorporate my JavaScript code into my page.jsx file efficiently?

Can I integrate this javascript code from a .js file into my .jsx file seamlessly? const { exportTraceState } = require("next/dist/trace"); const toggleBtn = document.querySelector('.toggle_btn') const toggleBtnIcon = document.querySe ...

Picking Layers on Google Maps with Three.js

I have incorporated the google-maps-api-threejs-layer library into my project from this source. Now, I am looking to implement a picking feature. Here is the modified code snippet: <!doctype html> <html> <head> <meta charset=&qu ...

Are your Promises.all functions executing at the incorrect timing?

I can't seem to understand why Promise.all is not working as expected. Even though the log shows that data for "Streak" and "Last Activity" is successfully retrieved towards the end, I want Promise.all to fetch the data only when everything is filled ...

The selected plugin appears to be incompatible with mobile browsers

My project involves implementing the Chosen plugin for a select field, allowing users to type-search through lengthy lists. It functions perfectly on desktop but is disabled on both Apple and Android phones, reverting to the default user interface for sele ...

My locale NUXT JavaScript files are being blocked by Content Security Policy

I've been working on implementing CSP headers for my website to ensure data is loaded from trusted sources. However, I'm facing an issue where CSP is blocking my local JS files. Here's a snippet from my nuxt.config.js: const self = 'lo ...

How can a controller in AngularJS detect when the back button of the browser is pressed

I've created a browser trivia game where authenticated players can select a game type, triggering a socket.io event in my Node.js server. The view then transitions to a "Searching for game" screen with a loading icon as the server waits for enough pla ...

Counting down in JavaScript until the desired MySQL datetime format is reached

I'm trying to display a countdown of hours and minutes to a date pulled from a MySQL database in the format 2010-09-24 11:30:12. I am not well-versed with dates in JavaScript, so any guidance would be greatly appreciated. Thank you. ...

What is the counterpart of the JavaScript transport.responseText in jQuery's Ajax requests?

I'm currently in the process of converting my JavaScript Ajax request to jQuery's ajax. Here is an example of my existing JavaScript Ajax code: new Ajax.Request(url, { method: 'post', onSuccess: function(transport) { ...

Avoid the issue of markers clustering in Leaflet to have distinct markerClusterGroup icons without overlap

Is there a way to prevent two separate markerClusterGroups from overlapping in Leaflet? I have one with a custom Icon to differentiate between the two clusters, but for simplicity's sake, I've omitted that part in this example. var map = L.map(&q ...

Tips for making sure a header is consistently at the top of every page during printing

I need help with my website - I have a table that is quite tall and spans across multiple pages when printing. Is there a way to make the header row appear on top of each page when printing? ...

Displaying dynamic text using radio buttons utilizing React

Currently, I am in the process of developing a multiple choice quiz where each question is presented with various options displayed as radio buttons. My main objective is to show specific text related to the option selected by the user when they make a ch ...

Can you please explain the function of this JavaScript code for the Isotope filter?

I am struggling to grasp the functionality of a section of vanilla JS code related to the Isotope filter. You can find the original code here. var buttonGroups = document.querySelectorAll('.button-group'); for (var i = 0; i < buttonGroups.le ...

Adding an onload event in a function-based component without using a fetch call

Looking at the code snippet below for a React component: import React from "react"; import { Carousel } from "react-bootstrap"; function CarouselHome() { return ( <> ...

Creating a factory class in Typescript that incorporates advanced logic

I have come across an issue with my TypeScript class that inherits another one. I am trying to create a factory class that can generate objects of either type based on simple logic, but it seems to be malfunctioning. Here is the basic Customer class: cla ...