What steps should one take to address issues related to Datatables in Laravel and Vue?

I encountered an issue while trying to fetch data into a datatable in Laravel. I am receiving an error message stating "Uncaught ReferenceError: $ is not defined" on the console of the page. Is there a solution to resolve this problem?

index.blade.php

@extends('layouts.app')
@section('header')
<link rel="stylesheet" href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css">
@endsection
@section('content')

<div class="container">
    @if(session("alert"))
        <div class="alert alert-{{ session(`alert-style`) }}">{{session("alert")}}</div>
    @endif
    <div class="row justify-content-center">
        <div class="col-md-8">
           
        <div class="mt-2 mb-2">
            <table id="productTable" class="table table-striped" style="width:100%">
            <thead>
                <tr>
                    <th>Title</th>
                    <th>Description</th>
                    <th>Price</th>
                </tr>
            </thead>
            </table>
            </div>
        </div>
</div>
</div>
@endsection

@section('footer')
       <component :is="'script'">
    
           $(function () {
    
            var table = $('#productTable').DataTable({
                processing: true,
                serverSide: true,
                ajax: "{{ route('product.getData') }}",
                columns: [
                    {data: 'title', name: 'title'},
                    {data: 'description', name: 'description'},
                    {data: 'price', name: 'price'},
                    {
                        data: 'action', 
                        name: 'action', 
                        orderable: true, 
                        searchable: true
                    },
                ]
            });
            
        });
        
        </component>
@endsection

ProductController.php

class ProductController extends Controller
{
    public function getData(Request $request)
    {
         $x = Product::select('id', 'title', 'description', 'price');
         return  Datatables($x)
               ->addColumn('edit', function($x){
                 return '<a href="'.route('product.edit', 
                 ['productId' => $x->id]).'">Edit</a>';})
               ->addColumn('delete', function($x){
                 return '<a href="'.route('product.delete', 
                 ['productId' => $x->id]).'">Delete</a>';})
               ->rawColumns(['edit','delete'])
               ->make(true);
    }
 }

web.php which specifies page routes is below.

Route::get('/product', [App\Http\Controllers\ProductController::class, 'index'])->name('product.index');
Route::post('/getData', [App\Http\Controllers\ProductController::class, 'getData'])->name('product.getData');

Answer №1

After downloading the js files locally and using them as a @vite expression, I was able to resolve the issue.

@vite(['resources/js/jquery.min.js', 'resources/js/jquery.dataTables.min.js'])
@section('footer')

       <component :is="'script'">
           $(function () {
    
            var table = $('#productTable').DataTable({
                processing: true,
                serverSide: true,
                ajax: "{{ route('product.getData') }}",
                columns: [
                    {data: 'title', name: 'title'},
                    {data: 'description', name: 'description'},
                    {data: 'price', name: 'price'},
                    {data: 'edit', name: 'edit', orderable: false, searchable: false},
                    {data: 'delete', name: 'delete', orderable: false, searchable: false}
                ],
                columnDefs: [{
                    "defaultContent": "-",
                    "targets": "_all"
                }]
            });
            
        });
        
        </component>
@endsection

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

When using the jQuery datepicker with the minDate set to 0, any past dates entered in the text box will be automatically reset to the current date

How can I prevent users from selecting past dates in a jQuery datepicker, while keeping any existing past dates displayed as is? My current code looks like this: $("#t1").datepicker({ minDate:0 }); And the text box code is, <input type="t1" va ...

Leverage the power of Reactjs to add hover effects to a mapped

I am facing a challenge in styling the ListItem on hover. The issue arises when the list is dynamically generated, causing all list items to change style simultaneously when hovered over. How can I target only one element for styling? Below is the code sni ...

All Material UI components are aligned in a single row, spanning the entire width of the page

These are the components I am currently working with: Sandbox: https://codesandbox.io/s/6ipdf?file=/demo.js:78-129 <FormControl sx={{ m: 1 }} variant="standard"> <InputLabel htmlFor="demo-customized-textbox">Age& ...

How can you make .ajax and params appear in this format?

I attempted to post a question earlier, but it seems like it was too complicated. Essentially, the request was for data to be formatted in a specific way, not from a form submission but generated through client-side search results. The desired format to ...

Perform a Selenium action to click on each individual HTML 'a' tag on

I am attempting to automate clicking on all the "a" tags within a website using Selenium in Python. However, I found that all the "a" tags I want to click have the same structure as shown in the code snippet below. I tried clicking them by their class si ...

Tips for transforming a container div into a content slider

Working with Bootstrap 3, a custom div has been created as shown below: <div class="second-para"> <div class="container"> <div class="second-section"> <div class="c ...

Tips for detecting when no checkboxes in a group are selected or when at least one checkbox is selected, and then applying a class to the corresponding div

<div class="accordion-group"> <div class="accordion-heading"> <a href="#collapse" data-parent="#accordionQuiz" data-toggle="collapse1.." class="accordion-toggle"> <strong>1...</strong> Question ...

How can you save the output of console.log in JavaScript to a variable and then use that variable in HTML?

Here is the code snippet I've been working on. The first part consists of JavaScript code, and the second part includes HTML. $('#table').on('check.bs.table', function (e, row) { checkedRows.push({First: row.fname, Second: row ...

Unveiling and Shifting Among Concealed HTML Forms

After going through numerous tickets with similar questions, I still can't seem to achieve what I want. So, I have no choice but to ask this question myself. I currently have an HTML page with 2 forms and 2 buttons. Both forms are initially hidden us ...

A dynamic search feature implemented with PHP, MySQL, and AJAX

I have implemented an ajax call to fetch data from my mysql database when searching for users. Below is the corresponding html code; <input type="text" id="partnerName" name="partnerName" class="form-control" placeholder="Type to search partners...."& ...

Integrating a fresh element into the carousel structure will automatically generate a new row within Angular

I'm currently working on an Angular4 application that features a carousel displaying products, their names, and prices. At the moment, there are 6 products organized into two rows of 3 each. The carousel includes buttons to navigate left or right to d ...

Present XML data on an HTML page to generate interactive form features

I have an application that features a checkbox tree. I would like to automatically pre-select those checkboxes if the user had previously checked them. To achieve this, I receive XML data from my backend Perl script which contains information on which che ...

The integration of Firebase Google Auth seems to encounter issues when used on the Vercel

My experience with Vercel deployment has been quite interesting. While I find that Google authentication works seamlessly on localhost, it seems to encounter an issue when deployed on Vercel. Specifically, after logging out, the currentUser variable always ...

Is there a way to eliminate empty arrays from my data?

I'm dealing with this PHP code snippet. public function display_children($parent,$level){ try { $cmd = $this->connection->prepare('SELECT mem,pid from mytree where pid = ?'); $cmd->execute(array($parent)); ...

Looping through a single object with an Ajax call

When I make this ajax call, it only displays the last object from the JSON file instead of all objects. Can someone help me understand why? Ajax Call var ajax = new XMLHttpRequest(); var data = 'data.json'; var url = 'http://localhost: ...

Leveraging Next.js to efficiently handle multiple asynchronous requests with NextResponse

I have developed a login/signup application using NextJS. When attempting to log in, the logic in my route.ts file sends requests to a MongoDB database to check if the user exists and if the password is correct. However, instead of receiving the expected 4 ...

Emphasize rows in the MUI-Datatables framework

A table was created using React.js and MUI-Datatables: import MUIDataTable from "mui-datatables"; const columns = ["Name", "Company", "City", "State"]; const data = [ ["Joe James", "Test Corp", "Yonkers", "NY"], ["John Walsh", "Test Corp", "Hartford", ...

Managing Numerous Dropdown Menus: Techniques and Tips

I'm currently working with MUI to design a navigation menu that contains dropdowns within certain links. However, I've encountered an issue where clicking on any button opens the same dropdown menu. Below is my code snippet: function Header() { ...

Is it possible to eliminate the use of the `this` keyword in a Vue.js application?

I am currently following the guidelines of Douglas Crockford's jslint, which gives a warning when 'this' is used. The warning displayed is: [jslint] Unexpected 'this'. (unexpected_a) I have not been able to find a solution for th ...

Query in MYSQL 8 to search for products within categories, specifically when the category is organized in a hierarchical structure and the product is linked to the lowest level category node

Table: categories id name parent 1 Electronic Gadgets null 2 Smart TVs 1 3 Portable Devices 1 4 CRT TVs 2 5 LCD TVs 2 6 Plasma TVs 2 7 Mp3 Players 3 8 CD Players 3 9 Flash Drives 7 Table: products (products linked to leaf category ...