php, Laravel 7 - Unable to receive data from AJAX request - javascript

I'm still a newbie and currently learning how to use Laravel 7.
My problem is, I tried to pass my data from the controller by using an AJAX request on
my child page. I noticed that when I tried to pass the data from my child page, the page won't
receive it but somehow it's working on a master page (where I didn't use any Blade directives).
I tried to dd() the data in the controller and it does show that there is data.
But it won't pass it to the child page. All the JS files and custom script that I push does
come out on the child page.
blade
code
index.blade.php (child page)
#extends('layouts.app')
#section('content')
<div class="container">
<div class="container mt-5">
<h2 class="mb-4">Laravel 7 Yajra Datatables Example</h2>
<table class="table table-bordered yajra-datatable">
<thead>
<tr>
<th class="text-center">#</th>
<th class="text-center">Name</th>
<th class="text-center">Batch</th>
<th class="text-center">Graduation Year</th>
<th class="text-center">Mobile</th>
<th class="text-center">Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
#endsection
#push('child-scripts')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/dataTables.bootstrap4.min.js"></script>
<script type="text/javascript">
$(function () {
var table = $('.yajra-datatable').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('alumni-list') }}",
columns: [
{data: 'DT_RowIndex', name: 'DT_RowIndex'},
{data: 'name', name: 'name'},
{data: 'batch_year', name: 'batch_year'},
{data: 'graduation_year', name: 'graduation_year'},
{data: 'contact_no', name: 'contact_no'},
{
data: 'action',
name: 'action',
orderable: true,
searchable: true
},
]
});
});
</script>
#endpush
AlumniController.php
class AlumniController extends Controller
{
public function index(Request $request)
{
// dd(Profile::latest()->get());
if ($request->ajax()) {
$data = Profile::latest()->get();
return Datatables::of($data)
->addIndexColumn()
->addColumn('action', function($row){
$btn = 'Edit Delete';
return $btn;
})
->rawColumns(['action'])
->make(true);
}
return view('admin.users.index');
}
}
Alumni Route
Route::get('alumni', [
'uses' => 'AlumniController#index',
'as' => 'alumni-list'
]);
Thank you for your time, sir.

Solved it after MORE googling done.
Make sure to add defer inside your DataTable CDN.
Example:
<script src = "http://cdn.datatables.net/1.10.18/js/jquery.dataTables.min.js" defer ></script>
Here's the link where I found the answer:
https://datatables.net/forums/discussion/50869/typeerror-datatable-is-not-a-function-datatable-laravel
For more understanding on why defer is added:
https://www.growingwiththeweb.com/2014/02/async-vs-defer-attributes.html

use Yajra\DataTables\Contracts\DataTable;
use Yajra\DataTables\Facades\DataTables;
please use this two line in your controller

Related

Datatables not displaying data (Laravel 8.4.x)

Hey there and thank you in advance.
Before describing my problem, I want to clarify that I have searched up the issue on Google and read through several posts, of which none helped me fix my problem.
That is why I'm adressing my problem personally here.
So basically I'm trying to display the 'users' table via the User model through DataTables on my Laravel application. When loading the page, the data does not appear (see Screenshot 1).
View (Folder 'resources/views/verwaltung' File 'nutzer.blade.php')
<head>
#extends('layouts.simple.master')
#section('title', 'Verwaltung - Nutzer')
#section('css')
#endsection
#section('style')
#endsection
#section('breadcrumb-title')
<h3>Nutzer</h3>
#endsection
#section('breadcrumb-items')
<li class="breadcrumb-item">Verwaltung</li>
<li class="breadcrumb-item active">Nutzer</li>
#endsection
<script src="{{ asset('assets/datatable/datatables/jquery.dataTables.min.js') }}" ></script>
<script src="{{ asset('assets/datatable/datatable/datatables/datatable.custom.js') }}" ></script>
</head>
#section('content')
<div class="container-fluid">
<div class="row">
<div class="col-sm-12">
<div class="card">
<div class="card-header">
<h5>Verwaltung / Nutzer</h5>
<span>Hier kannst du die Nutzer der Seite bearbeiten</span>
</div>
<div class="card-body">
<h2 class="mb-4">Nutzer</h2>
<table class="table table-bordered nutzerverwaltung">
<thead>
<tr>
<th>ID</th>
<th>Nickname</th>
<th>Email</th>
<th>Teamrank</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
#endsection
#section('script')
<script type="text/javascript">
$(function () {
var table = $('.nutzerverwaltung').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('verwaltung.nutzer.list') }}",
columns: [
{data: 'DT_RowIndex', name: 'DT_RowIndex'},
{data: 'id', name: 'id'},
{data: 'name', name: 'name'},
{data: 'email', name: 'email'},
{data: 'teamrank', name: 'teamrank'},
{
data: 'action',
name: 'action',
orderable: true,
searchable: true
},
]
});
});
</script>
#endsection
Controller (Folder 'app/Http/Controllers' File 'UserController.php')
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use DataTables;
class UserController extends Controller
{
public function index()
{
return view('verwaltung.nutzer');
}
public function getUsers(Request $request)
{
if ($request->ajax()) {
$data = User::latest()->get();
return Datatables::of($data)
->addIndexColumn()
->addColumn('action', function($row){
$actionBtn = 'Edit Delete';
return $actionBtn;
})
->rawColumns(['action'])
->make(true);
}
}
}
Routes (Folder 'routes' File 'web.php') - (just the relevant part)
Route::get('verwaltung.nutzer', [UserController::class, 'index'])->name('verwaltung.nutzer');
Route::get('verwaltung.nutzer.list', [UserController::class, 'getUsers'])->name('verwaltung.nutzer.list');
Model (Folder 'app/Models' File 'User.php')
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'id',
'name',
'email',
'password',
'teamrank',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Any help would be greatly appreciated.
Thanks!

Datatable for pagination and searching for live data?

I tried using datatables for live data but my problem is, every time my data updates, I can't use searching and every time I use pagination, it goes back to first page. Can somebody knows what datatable plugin is compatible with angular?
Here is my code for realtime update of data:
angular.module('selectExample', [])
.controller('ExampleController', ['$scope','$interval', function($scope,$interval) {
$interval(function () {
$scope.register = {
regData: {
branch: {},
},
names: [
{name:"narquois"},{name:"vorpal"},{name:"keen"},
{name:"argol"},{name:"long"},{name:"propolis"},
{name:"bees"},{name:"film"},{name:"dipsetic"},
{name:"thirsty"},{name:"opacity"},{name:"simplex"},
{name:"jurel"},{name:"coastal "},{name:"fish"},
{name:"kraken"},{name:"woman"},{name:"limp"},
],
};
}, 1000);
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="selectExample" ng-controller="ExampleController">
<table id="example" width="100%">
<thead>
<tr align="center">
<th>Name</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="person in register.names">
<td align="center">{{ person.name }}</td>
</tr>
</tbody>
</table>
</div>
Enable state saving and override state save/load handlers to use only the table's DOM id:
$('#example').dataTable( {
stateSave: true,
stateSaveCallback: function(settings,data) {
localStorage.setItem( 'DataTables_' + settings.sInstance, JSON.stringify(data) )
},
stateLoadCallback: function(settings) {
return JSON.parse( localStorage.getItem( 'DataTables_' + settings.sInstance ) )
}
} );
You have to initialize your DataTable with the option stateSave. It enables you to keep the pagination, filter values, and sorting of your table on page refresh. It uses HTML5's APIs localStorage and sessionStorage.
$('#example').dataTable( {
stateSave: true
});

Datatables Not Loading Nested Objects Ajax

Trying to get my ajax to load into data tables. I want to load 2 tables from the same ajax call but I can't even get 1 to load first. Let's get some snippet action going...
$(function() {
$("#tablepress-1").DataTable({
ajax: {
url: '/api/?action=getStats',
dataSrc: 'data',
"deferRender": true
},
"columns": [{
"instances": "Strategy"
},
{
"instances": "Exchange"
},
{
"instances": "Trades"
},
{
"instances": "PL"
},
{
"instances": "Uptime"
}
]
})
})
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<table id="tablepress-1" class="tablepress tablepress-id-1">
<caption style="caption-side:bottom;text-align:left;border:none;background:none;margin:0;padding:0;">Edit</caption>
<tbody>
<tr class="row-1">
<td class="column-1">Strategy</td>
<td class="column-2">Exchange</td>
<td class="column-3">Trades</td>
<td class="column-4">PL</td>
<td class="column-5">Uptime</td>
</tr>
</tbody>
</table>
Since stack snippets don't support ajax data, I'll paste it here:
{"success":true,"data":{"instances":[{"Strategy":"...","Exchange":"...","Trades":"...","PL":"...","Uptime":"..."}],"trades":[{"Open":"...","Strategy":"...","Exchange":"...","Direction":"...","Size":"...","PL":"...","Close":"...","ID":"..."}]},"meta":{"botOnline":true,"threadCount":0,"balance":0.0028}}
Right now I just have my script outputting ... for each field. What happens is that the table headings disappear and no data ever gets loaded into the table.
I tried setting up a fiddle with the data source but it's my first time trying to use the echo feature. Maybe someone else knows how to do that: https://jsfiddle.net/Trioxin/kjhtn7wm/6/
I can't imagine what's wrong here. I thought I specified the json format properly but it appears not.
Regarding cross domain AJAX sources in jsfiddles you can use http://myjson.com
Your "table headings" disappear because they are not table headings. They are just a <tbody> row that will be removed as soon DataTables get some data. Do this instead:
<thead>
<tr class="row-1">
<th class="column-1">Strategy</th>
<th class="column-2">Exchange</th>
<th class="column-3">Trades</th>
<th class="column-4">PL</th>
<th class="column-5">Uptime</th>
</tr>
</thead>
You must either pass an array of objects or point to the path of that array, like dataSrc: data.instances. You could also have dataSrc: function(data) { return data.data.instances }
You define which object property that should be mapped into which column through the data option like { data: "Strategy" }:
columns: [
{ data: "Strategy" },
{ data: "Exchange" },
{ data: "Trades" },
{ data: "PL" },
{ data: "Uptime" }
]
forked fiddle -> https://jsfiddle.net/hfc10sxt/

ASP MVC and Datatables: error getting data via ajax

I'm trying to load data in datatables (1.10.9) via ajax to an ASP MVC controller.
I have the following table:
<table id="Demo" class="table table-striped" cellspacing="0">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Code)
</th>
<th>
#Html.DisplayNameFor(model => model.Description)
</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
And the following script
<script>
$(document).ready(function () {
$('#Demo').DataTable({
ajax: 'GetVehicle',
dataSrc: '',
columns: [
{ data: 'Code' },
{ data: 'Description' }
]
});
});
</script>
In ASP MVC i have the following Controller:
[HttpGet]
public JsonResult GetVehicle()
{
return Json(db.vehicletype.ToList(), JsonRequestBehavior.AllowGet);
}
And when this controller is called by the ajax request in the chrome inspector i see the following answer:
[
{"vehicle":[],"Id":1,"Code":"Car1","Description":"Car1 Description"},
{"vehicle":[],"Id":2,"Code":"Car2","Description":"Car2 Description"}
]
Why in the datatables i don't see any rows? I only see "Loading...."
In the chrome inspector, in the console, i see only this error:
Uncaught TypeError: Cannot read property 'length' of undefined
in the jquery.dataTables.min.js
UPDATE
Resolved changing the asp mvc controller into:
public JsonResult GetVehicle()
{
return Json(new { data = db.vehicletype.ToList() }, JsonRequestBehavior.AllowGet);
}

Rendering Ember view with helpers

I have read the ember guide to achieve the same in my Ember Application, but i can't.
I am trying to configure my view with a Controller which makes a multiplication between two values
Here the code:
App.TotalView = Ember.View.extend({
attributeBindings: ['value', 'placeholder'],
placeholder: null,
value: '',
total: (function() {
return this.get('newThread.selectContentTariffa') * this.get('newThread.primary');
}).property('newThread.selectContentTariffa', 'newThread.primary')
});
Here in the view:
<td>{{view "total" valueBinding=newThread.value}}</td>
I can not get the result of this multiplication in this view,is this code correct? what's wrong?
You can see here: http://emberjs.jsbin.com/qakado/edit
By only focusing on the issue you are facing and not the design and based on the code you have provided, there are the following issues and corresponding possible solutions applied to the examples at the end,
there are calls to newThread but it is not defined anywhere - create a newThread in controller
the view helper uses total you may either create a template and associate it with App.TotalView or use the block form of view helper - 1st example uses a template, 2nd uses block form
js
App.ThreadsController=Ember.ArrayController.extend({
selectContentTariffa: [
{label: "180", value: "180"},
{label: "200", value: "200"},
{label: "300", value: "300"}
],
newThread:{
value:null,
selectContentTariffa:null,
primary:null
}
});
App.TotalView = Ember.View.extend({
templateName:"total",
attributeBindings: ['value', 'placeholder'],
placeholder: null,
value: '',
total: (function() {
var res= parseInt(this.get('controller.newThread.selectContentTariffa')) * parseInt(this.get('controller.newThread.primary'));
return isNaN(res)?"":res;
}).property('controller.newThread.selectContentTariffa', 'controller.newThread.primary')
});
hbs - example1
<script type="text/x-handlebars" data-template-name="threads">
<table class="table table-bordered table-hover">
<tr><th>Title 1</th><th>Title 2</th><th>Title 3</th></tr>
<tr>
<td>{{view Ember.Select prompt="Tariffa" valueBinding=newThread.selectContentTariffa content=selectContentTariffa optionValuePath="content.value" optionLabelPath="content.label"}}</td>
<td>{{view Em.TextField type="number" valueBinding=newThread.primary class="form-control"}}</td>
<td>{{view "total"}}</td>
</tr>
</table>
</script>
<script type="text/x-handlebars" data-template-name="total">
this is total:{{view.total}}
</script>
hbs-example2
<script type="text/x-handlebars" data-template-name="threads">
<table class="table table-bordered table-hover">
<tr><th>Title 1</th><th>Title 2</th><th>Title 3</th></tr>
<tr>
<td>{{view Ember.Select prompt="Tariffa" valueBinding=newThread.selectContentTariffa content=selectContentTariffa optionValuePath="content.value" optionLabelPath="content.label"}}</td>
<td>{{view Em.TextField type="number" valueBinding=newThread.primary class="form-control"}}</td>
<td>{{#view "App.TotalView"}}t:{{view.total}}{{/view}}</td>
</tr>
</table>
</script>
example1 - http://emberjs.jsbin.com/falafezijo/edit?html,js
example2 - http://emberjs.jsbin.com/cuxafigiqe/1/edit?html,js

Categories

Resources