Datatable does not work in Laravel 9 & Vite; Error jQuery is not defined - laravel

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" class="table table-bordered table-striped table-hover sizethtd">
<tr>
<th class="">Name</th>
<th class="">Email</th>
<th class="">Address</th>
<th class="">Action</th>
</tr>
#foreach ($clients as $client)
<tr>
<td>{{ $client->name }}</td>
<td class="">{{ $client->email }}</td>
<td class="">{{ $client->address }}</td>
<td>
<a class="btn btn-info" 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

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/

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

DomPDF is displaying output as HTML not as PDF document

I'm facing an issue with domPDF. pdf result getting displayed as html page not as pdf document. I'm trying to get the data from database and get the result in pdf document using 'dompdf' for laravel.
pdf-output-image
here is my HTML code.
`<!DOCTYPE html>
<html>
<head>
<title>MHT Order PDF</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
</head>
<body>
<div class="d-block text-center" style="text-align: center; margin-top: -15px;">
<h1 style="text-align: center" class="navbar-brand text-underline text-center"><u> MAJESTIC HOUSE </u></h1>
<p style="margin-top:-20px">General Trading LLC</p>
</div>
<div class="order_heading">
#foreach($orderDtls as $order)
<p class="date">Date: {{$date}}</p>
<h3 class="orderDtls">Order Details </h3>
<h5 class="details">Order UID: <strong style="color: red;">{{$order->order_unq_id}}</strong></h5>
<h5 class="details">Customer Name: <strong style="color: red;">{{$order->customer_name}}</strong></h5>
<p id="date"> </p>
</div>
<table class="table caption-top" id="orderTable">
<caption>Order Details</caption>
<thead>
<tr>
<th scope="col">Customer Name</th>
<th scope="col">Product Name</th>
</tr>
</thead>
<tbody>
#foreach($orderDtls as $order)
<tr>
<td scope="row">{{$order->customer_name}}</td>
<td>{{$order->item_name}}</td>
</tr>
#endforeach
</tbody>
</table>
#endforeach
</body>
</html>
this is the code from Controller
public function mht_order_pdf(){
$customers = Customer::all();
$linkeds = Linked::all();
$orders = Order::all();
$date = date('y-m-d');
$orderDtls = DB::select("SELECT
customers.customer_name,
orders.id,
orders.order_unq_id,
items.item_name,
orders.item_quantity,
orders.total
FROM customers
JOIN linkeds
ON customers.id = linkeds.customer_id
JOIN items
ON linkeds.item_id = items.id
JOIN orders
ON linkeds.id = orders.linked_id
WHERE orders.order_unq_id = 'MH-Ord/29722/xyz supermarket';"
);
// // return $orderDtls;
return view('mht_order_pdf', compact('customers', 'linkeds', 'orders', 'orderDtls',
'date'));
$pdf = PDF::loadView('mht_order_pdf', $orderDtls);
return $pdf->stream('mht_order_pdf.pdf');
}
this is the code from web.php
<?php
use App\Http\Controllers\Backend\CustomerController;
use App\Http\Controllers\Backend\ItemController;
use App\Http\Controllers\Backend\LinkedController;
use App\Http\Controllers\Backend\OrderController;
use App\Http\Controllers\Backend\ProductController;
use App\Http\Controllers\Backend\UserController;
use App\Http\Controllers\PDFController;
use App\Models\Customer;
use App\Models\Linked;
use App\Models\Order;
use App\Models\Product;
use Illuminate\Support\Facades\Route;
use Dompdf\Dompdf;
use Illuminate\Support\Facades\DB;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])-
>name('home');
Route::resource('users', UserController::class);
Route::resource('products', ProductController::class);
Route::resource('items', ItemController::class);
Route::resource('customers', CustomerController::class);
Route::resource('linked', LinkedController::class);
Route::resource('orders', OrderController::class);
Route::get('mht_order_pdf', [OrderController::class, 'mht_order_pdf'])-
>name('mht_order_pdf');
PLEASE LET ME KNOW WHAT I'M DOING WRONG?
Thank you!
Your controller stops at this line:
return view('mht_order_pdf', compact('customers', 'linkeds', 'orders', 'orderDtls', 'date'));
thus the 2 lines below it, which related to the DomPDF, gets ignored. Try to delete the return view() above so that the DomPDF lines of code below it can be executed.

Im confuse with axios in seperate service file

Im now is learn vue.js, and i want to consume API from my backend (using spring).
This is my service.js
import axios from "axios";
class LowonganKerjaService {
retrieveAllLoker() {
return axios.get('http://localhost:8081/api/listLoker');
}
deleteLoker(idLowongan){
return axios.delete('http://localhost:8081/api/${idLowongan}');
}
}
export default new LowonganKerjaService();
this is my component
<template>
<div class="container">
<h3>All Courses</h3>
<div v-if="message" class="alert alert-success">
{{message}}
</div>
<div class="container">
<table class="table">
<thead>
<tr>
<th>Id</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr v-for="loker in loker" v-bind:key="loker.idLowongan">
<td>{{loker.idLowongan}}</td>
<td>{{loker.deskripsi}}</td>
<td>
<button class="btn btn-warning" v-on:click="deleteLokerClicked(loker.idLowongan)">
Hapus
</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</template>
<script>
import LowonganKerjaService from '../../service/LowonganKerjaService';
export default {
name : "LokerList",
data() {
return{
loker : []
};
},
methods:{
refreshLoker(){
LowonganKerjaService.retrieveAllLoker()
.then(response => {
this.loker = response.data;
});
},
deleteLokerClicked(idLowongan){
LowonganKerjaService.deleteLoker(idLowongan).then(()=> {
this.message = 'Loker dengan ${idLowongan} berhasil dihapus';
this.refreshLoker();
});
}
},
created(){
this.refreshLoker();
}
};
</script>
<style>
</style>
and i got this error
Failed to compile.
./src/service/LowonganKerjaService.js Module Error (from
./node_modules/eslint-loader/index.js):
D:\Kuliah\TERM
6\Propensi\Implementasi\frontend-sixacti\src\service\LowonganKerjaService.js
10:17 error 'idLowongan' is defined but never used no-unused-vars
✖ 1 problem (1 error, 0 warnings)
Oh and i've got error too when i use ${} in those service.
Why that error state that my 'idLowongan' is never used? is it because i wrong my syntaks or what?
Please somebody help me to give the reason
Thanks
**sorry for my bad language
From the looks of your code it looks like you're using a single quote (') and not a backtick (`) when you're attempting to use JS template literal. You can see an example of that in the MSDN documentation. Since it is a string in your example and not a template literal the variable in the function's argument is never used.
Try changing the code in your service's delete method to be this:
return axios.delete(`http://localhost:8081/api/${idLowongan}`)

How to populate the v-data-table after an AJAX request to fetch the data using Vuetify in Laravel?

Using VueJS with Vuetify and in Laravel framework. Many different methods of AJAX and defining components were tried but nothing worked. It seems that when the ajax call is made, the variable is updated, which I checked in the console.log, but it is not reflected in the DOM.
My current code is as follows
Method 1
In the home.blade.php
<div id="items-display-table">
#{{itemslist}}
<v-data-table
:items="itemslist"
class="elevation-1"
hide-actions
hide-headers
>
<template slot="items" slot-scope="props">
<td>#{{ props.item.name }}</td>
<td class="text-xs-right">#{{ props.item.calories }}</td>
<td class="text-xs-right">#{{ props.item.fat }}</td>
<td class="text-xs-right">#{{ props.item.carbs }}</td>
<td class="text-xs-right">#{{ props.item.protein }}</td>
<td class="text-xs-right">#{{ props.item.iron }}</td>
</template>
</v-data-table>
</div>
And in the app.js
var itemsDisplayTable = new Vue({
el: '#items-display-table',
data: {
itemslist: []
},
created: function () {
this.fetchData();
},
methods: {
fetchData: function () {
var self = this;
var apiURL = '/api/cards';
axios.get( apiURL )
.then ( function( response ) {
data = response['data'];
// console.log(data);
self.itemslist = data;
console.log(self._data);
});
}
}
});
Method 2
Alternatively, I have also tried building a component with the data passed as a prop to solve the reactive issue but still it doesn't work.
The code for that is as follows in home.blade.php
<div id="cards-display-table">
<grid
:itemslist="itemslist">
</grid>
</div>
In app.js
Vue.component('grid', require('./components/DataTable.vue'));
And the instance creation is same as above.
The code in the DataTable.vue file is as follows
<template>
<div>{{itemslist}}</div>
<v-data-table
:items="itemslist"
class="elevation-1"
hide-actions
hide-headers
>
<template slot="items" slot-scope="props">
<td>#{{ props.item.name }}</td>
<td class="text-xs-right">#{{ props.item.calories }}</td>\
<td class="text-xs-right">#{{ props.item.fat }}</td>\
<td class="text-xs-right">#{{ props.item.carbs }}</td>\
<td class="text-xs-right">#{{ props.item.protein }}</td>\
<td class="text-xs-right">#{{ props.item.iron }}</td>\
</template>
</v-data-table>
</template>
<script>
export default {
props: {
itemslist: Array
}
}
</script>
How should i proceed?
I found a solution to my question. It was a pretty silly mistake. So just in case, anyone faces it again, I have decided to answer it.
The problem was that I was registering a new root component to display the items in the app.js file. And it is clearly mentioned that for the Vuetify components to work, they must be wrapped in the <v-app>. So I put the components in a single file and now it is working perfectly.

Vue Component not works even i register it follow the official manual

just a very new to Vue 2.0, i actually use if for Laravel 5.4, now you can see from below link that i created one component which name is "canvas-chart", what actually i want show is a filterable table, and then to get more Json data from next steps, but now it always show me "Unknown custom element: - did you register the component correctly? For recursive components, make sure to provide the "name" option." , can not understand that i follow the official documentation to use it why it's not work?
new Vue({
el:'#filterTest',
data:{
keywords:[{"id":"9","name":"missy","phone":"21324234532"},
{"id":"3","name":"Mahama","phone":"345604542"},
{"id":"2","name":"Bernard","phone":"241242542"}]
},
computed: {
filterM: function () {
var self = this
return self.filter(function (word) {
return user.name.indexOf(self.searchQuery) !== -1
})
}
}
});
Vue.component('canvas-chat',{
template:'#canvasChart',
props:['keywordsData']
})
<script type="text/x-template" id="canvasChart">
<table>
<thead>
<tr>
<th v-for="key.id in keywordsData">
<span class="arrow" ></span>
</th>
</tr>
</thead>
<tbody>
<tr v-for="key.name in keywordsData">
<td v-for="key.phone in keywordsData"> {{key.name}}</td>
</tr>
</tbody>
</table>
</script>
<div id="filterTest">
<canvas-chat keywordsData="keywords" ></canvas-chat>
</div>
You have a few issues:
You must register the canvas-chat component first before you use it in the main component (put Vue.component('canvas-chat', ... before new Vue(...)).
Your v-for loops are wrong. They should be like v-for="key in keywordsData", not v-for="key.id in keywordsData".
The v-fors on the tr and td elements don't make sense; you will have to process the keywordsData first (perhaps in a computed property) to get it into the correct format you want, then loop over that.
You must bind the keywordsData prop in the template like this: :keywords-data="keywords".

Rendering table in bllim datatables Laravel 4

I don't know how to render datatable in view, here is the code in my controller.
public function getTable()
{
$tasks = Todo::select(array('todos.id','todos.task','todos.deadline','todos.status'));
return Datatables::of($tasks)->make();
}
Any help will be appreciated.
You need to create the datatable structure in your view and call the controller method with jQuery.
For example in your view you can set the following html:
<table id="tasks" class="table table-striped table-hover">
<thead>
<tr>
<th class="col-md-3">ID</th>
<th class="col-md-3">Task</th>
<th class="col-md-3">Deadline</th>
<th class="col-md-3">Status</th>
</tr>
</thead>
</table>
And then add the following jQuery that calls your controller action
<script type="text/javascript">
var oTable;
$(document).ready(function() {
oTable = $('#tasks').dataTable( {
"sPaginationType": "bootstrap",
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "{{ URL::to('tasks/getTable') }}"
});
});
</script>
You also need to reference the following files in your page
http://code.jquery.com/jquery-1.10.2.min.js
and
http://cdn.datatables.net/1.10.0/js/jquery.dataTables.js
and also add the Controller/getTable method to your routes file (in the example above I wrote it as tasks/getTable
If you need features like filters, sorting, etc., try Nayjest/Grids package for Laravel. If you need just simple table -- previous response is preferred.

Resources