Retrieve custom content from a database using Laravel and Ajax when clicking on a navigation bar

Recently, I've started working with Laravel 7 and AJAX. One of the features I want to implement is a 'product's name' navbar that displays product details in a div without refreshing the page when clicked. I came across a demo showcasing this functionality in PHP ( ), but I aim to achieve this in Laravel.

Here is a snippet of the blade part:

<ul class="nav navbar-nav">
    <?php
    $group = DB::table('package')->where('group_id', 5)->get();

    ?>
    @foreach ($group as $item)
        <li id="{{ $item->package_id }}"><a href="#">{{$item->package_name  }}</a></li>
    @endforeach
</ul>
<span id="page_details"></span>

And here is the script part for the AJAX on the blade file:

<script>
    $(document).ready(function () {

        function load_page_details(id) {
            $.ajax({
                type: 'POST',
                url: '/getmsg',
                data: '_token = <?php echo csrf_token() ?>',
                data: {id: id},
                success: function (data) {
                    $('#page_details').html(data);
                }
            });
        }

        load_page_details(1);

        $('.nav li').click(function () {
            var page_id = $(this).attr("id");
            load_page_details(page_id);
        });
    });
</script>

Defined route:

Route::post('/getmsg','AjaxController@index');

And the corresponding controller method:

public function index(Request $request) 
{
    $pack_id=$request->id;
    $msg = DB::table('package')->where('package_id',$pack_id);
    $output .= '
    <h1>'.$msg->package_id.'</h1>
    
    ';

    return  $output;
 }

I would appreciate any assistance in creating a similar dynamic content loading feature in Laravel like the one demonstrated here ( ).

Answer №1

Initially, it is important to note that there are 2 data attributes in your ajax request. It is recommended to combine them into a single one:

data: { "_token" : "{{ csrf_token() }}", "id" : id} 

Additionally, I suggest specifying the dataType as json in the AJAX request and returning a json response from the controller instead of using $output = ...

return response()->json(['package_id' => $msg->package_id]);

Subsequently, within your .success callback function, you can access the data properties just like you would with a standard javascript object. To achieve your objective, you can utilize

$('#page_details').html(data.package_id)
.

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

Ways to acquire the reference of the parent component

Within my code, there is a parent component represented as: <Parent> <Child (click)=doSomething()></Child> </Parent> I am looking to establish a reference to the Parent component in order to pass it within a method that will trigg ...

I keep encountering an error that says "ReferenceError: localStorage is not defined" even though I have already included the "use

I have a unique app/components/organisms/Cookies.tsx modal window component that I integrate into my app/page.tsx. Despite including the 'use client' directive at the beginning of the component, I consistently encounter this error: ReferenceErr ...

Does the entire state get replaced every time a change is made if the state is immutable?

Is it necessary to replace the entire state if it is immutable? Otherwise, wouldn't mutating the state occur? Are top-level keys maintained as distinct immutable objects? Wouldn't changing anything necessitate replacing the entire state by defin ...

Having trouble getting the .push() method in JavaScript to function correctly

I've encountered an issue while trying to develop a function that iterates through each item in an array and records the index of a specific item when found. In this particular function, whenever the item 'contraband' is detected during the ...

Discover a foolproof method for effortlessly examining an flv or mp4 file embedded within a webpage simply by

I've encountered a challenge with JavaScript. I can successfully check a flash object in a webpage when hovering over it, but I'm unsure how to achieve the same for flv or mp4 objects when either hovering over or moving away from them. Currently ...

Tips for loading a webpage directly to the center instead of the top position

Is there a way to make the page open at a specific div halfway down the page instead of starting from the top? Here is an example: <div id="d1"> <div id="d2"> <div id="d3"> <div id="d4"> <div id="d5"> <div id="d6"> Do ...

TranslateY animation glitching

I need help with expanding a box to 100% height after click, then collapsing and sticking to the bottom. I created a function in Vue framework to handle the animation, but it's not working smoothly. How can I make it less buggy? Check out the demo her ...

Obtain a numerical output from a selection of numbers

I am facing a simple problem that I can't solve due to my lack of knowledge and have not been able to find any solution online. What I want to achieve is: Create a "value 1" from an array of integers. Generate a random "value 2". Check if the rando ...

How to toggle between displaying divs using JavaScript and Jquery

How can I use JavaScript to show or hide specific divs on page load and upon clicking different links? I want to display the "houseImages" div by default, while hiding the "landImages", "renovationImages", "UpcomingImages", and "voteForNext" divs. Then, w ...

When using Laravel's Response::json, a cross-domain error may still occur in the browser despite setting the header to Access-Control-Allow-Origin

I am facing a perplexing Laravel 4 issue. I have set up two methods in the same controller, which is declared to be restful. The problem arises when the ajax request comes from a different domain. The first method does not work: public function getOwnlis ...

Is there a way to determine the negative horizontal shift of text within an HTML input element when it exceeds the horizontal boundaries?

On my website, I have a standard HTML input field for text input. To track the horizontal position of a specific word continuously, I have implemented a method using an invisible <span> element to display the content of the input field and then utili ...

What is the best way to trigger an event using vue-chartjs?

I am using vue js to display a graph with chartjs. I have implemented an onClick function on the graph to emit an event in the parent component and retrieve data. However, the event is not working as expected. Can you help me identify the issue? Component ...

Tips for updating the value within a textfield in HTML

I am looking to dynamically update the value displayed in my Revenue textfield by subtracting the Cost of Goods from the Sales Price. I have included an image of the current layout for reference, but I want the Revenue field to reflect the updated value af ...

Troubleshooting: Vue.js file upload encountering OPTIONS 404 error

In my express app, I have configured CORS and most of the routes are working fine. However, I'm facing an issue with a specific component used for uploading images: <input type="file" class="form-control" @change="imageChanged"> <div @clic ...

Animate.css bxSlider text animations

As I am in the process of setting up a slider for my website, I have encountered some issues. I am utilizing bxslider and wished to incorporate animations for the text on each slide by integrating animate.css. Animate.css is quite simple: just add "animat ...

Node.js VAR DeclarationIn the world of Node.js, we make

I am currently expanding my knowledge on Node.js. I came across a line in my book that has sparked my curiosity, and I wanted to seek some clarification. The specific line in question is: var user = req.user = users[req.params.name]; After doing some re ...

The error code 13:5 indicates that the "Home" component has been registered in the Vue application but is not being used, leading to the error message "vue/no-unused-components"

I encountered this issue while working with Vue for the first time. I was attempting to construct a website using Vue/CLI by reorganizing and building from the inside out. However, I am unfamiliar with Vue and unsure how to resolve this error. The changes ...

Using webpack to load the css dependency of a requirejs module

Working with webpack and needing to incorporate libraries designed for requirejs has been smooth sailing so far. However, a bump in the road appeared when one of the libraries introduced a css dependency: define(["css!./stylesheet.css"], function(){ &bsol ...

Display the number of rows per page on the pagination system

Looking for a way to add a show per page dropdown button to my existing pagination code from Mui. Here's the snippet: <Pagination style={{ marginLeft: "auto", marginTop: 20, display: "inline-b ...

Utilizing Vue 3 to transform an item within a list by referencing its index

Storing the element's index in a global variable is causing issues when trying to individually edit each of them. Adding multiple elements with similar properties but being unable to edit them separately due to alterations affecting the rest is a chal ...