Home > Enterprise >  Datatable does not work in Laravel 9 & Vite; Error jQuery is not defined
Datatable does not work in Laravel 9 & Vite; Error jQuery is not defined

Time:08-12

I am trying to add datatable in my Laravel 9 project (I use Vite).

I noticed it doesn't work because I'm getting these two errors:

First error:

$ is not defined

Second error:

jQuery is not defined

This is my complete code:

bootstrap.js

try {
    window.Popper = require('popper.js').default;
    window.$ = window.jQuery = require('jquery');

    require('bootstrap');
    require('datatables.net');
} catch (e) {}

app.js

import './../../node_modules/datatables.net/js/jquery.dataTables';

view

<table id="tableclient" >
            <tr>
                <th >Name</th>
                <th >Email</th>
                <th >Address</th>
                <th >Action</th>
            </tr>
            @foreach ($clients as $client)
            <tr>
                <td><a href="{{route('client.show' , compact('client'))}}" >{{ $client->name }}</a></td>
                <td ><a href= "mailto:{{ $client->email }}" >{{ $client->email }}</a></td>    
                <td >{{ $client->address }}</td>
                <td>                     
                <a  href="{{route('project.create', compact('client'))}}">Add</a>
                </td>
            </tr>
        @endforeach
    </table>

<script>

        $(function () {
            $('#tableclient').DataTable({
                processing: true,
                serverSide: false
            });
        });

    </script>

vite.cofig.js

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';

export default defineConfig({
    plugins: [
        laravel({
            input: [
                'resources/css/app.css',
                'resources/js/app.js',
            ],
            refresh: true,
        }),
    ],
});

Could anyone kindly help me?

UPDATE

I installed jquery via the command

npm i jquery

and in app.js I imported, along with datatable, the following line:

import './../../node_modules/jquery/src/css';

The error still continues to exist

CodePudding user response:

You're just missing jQuery. There's various ways to add jQuery,one quick way but not idael way is to add by cdn

<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj 3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>

https://releases.jquery.com/

CodePudding user response:

It seems you are missing the Jquery CDN link.

You may use

<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj 3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>

Or By Installing it manually, by:

npm install jquery

or

yarn add jquery

Inside your bootstrap.js or app.js use

window.$ = window.jQuery = require('jquery')

Then require js/app.js inside your app.

  • Related