Datatables 'No Match Found' - php

I have a datatable that I'm using in server-side mode to retrieve data via AJAX. On the surface everything appears correct however, when I load the page I get "No Matching Records Found" displayed instead of the data displaying. The peculiar part is that it says it is showing the records "Showing records 1 to 2 of 2 entries".
The table HTML and JS is as follows:
<div class="container">
<script type="text/javascript">
$(document).ready(function() {
$("#freebieslist").dataTable({
"bServerSide": true,
"sAjaxSource": "/config/getadvertisers",
"bPaginate": true,
"bProcessing": true,
"bFilter" : true,
"sPaginationType" : "bootstrap",
"sDom": "<'row'<'span6'l><'span6'f>r>t<'row'<'span6'i><'span6'p>>"
});
$.extend( $.fn.dataTableExt.oStdClasses, {
"sWrapper": "dataTables_wrapper form-inline"
} );
});
</script>
<div class="row"><h1 class="pull-left">Advertisers</h1><div class="pull-right" style="margin-top:15px;">Add New Delete</div> </div>
<div class="row">
<div class="span12">
<table id="freebieslist" class="table table-bordered table-striped table-hover">
<thead>
<tr>
<th class="span1"> </th><th>Advertiser</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div> </div>
The JSON being loaded is this:
{
"sEcho": "1",
"iTotalRecords": "2",
"iTotalDisplayRecords": "2",
"aaData": [
[
"2",
"Test2"
],
[
"1",
"Tester"
]
]
}
How to fix this so it actually displays the returned rows?

I solved the issue by using datatables debugger in Chrome. I checked the AJAX result coming back (based on the get paramaters datatables was passing in) and found it was getting a null result set. A quick change in the server side code and things started working properly.

Related

Responsive table in DataTable

My page looks like this:
I want to add scrollX when page is too small so I must add line
scrollX: true
When I add page looks like this:
DataPicker is behind rows and line of column is not in this same line but scrollX work(look picture). When I write in input and ajax load data that line of column works fine but datapicker still not work. How can I repair this?
Code _table.blade.php
<table class="table table-striped table-bordered" id="policies-table" style="width: 100%;">
<thead>
<tr>
<th>Numer polisy</th>
<th>Produkt</th>
<th>Data wystawienia</th>
<th>Wartość</th>
<th>Składka</th>
<th>Wystawiający</th>
<th>Akcje</th>
</tr>
</thead>
</table>
Ajax load:
$('#policies-table').DataTable({
ajax: {url:"url",
type: "POST",
'headers': {'X-CSRF-TOKEN': '{{ csrf_token() }}'}},
processing: true,
serverSide: true,
autoWidth: true,
scrollX: true,
scrollCollapse: true,
jQueryUI: true,
order: [[ 2, "desc" ]],
........
});
Try this $('#policies-table').DataTable({responsive: true} );
Or If you are using bootstrap, you cant try this
<div class='table-responsive'>
<table class='your classes'>
</table>
</div>

Laravel 5.5 - Pass MySQL query to Javascript function/DataTables

I'd like to pass a SQL query to a Javascript function, found in my view, which will populate a HTML table using the DataTables API. I'm having trouble converting the object array into plain JSON. How would I go about doing so?
[web.php]
Route::get('/admin', function () {
$users = DB::connection('mysql')->select('SELECT * FROM users');
return view('admin', compact('users'));
});
[admin.blade.php] (HTML)
<div class="row">
<div class="col-lg-6">
<div class="card mb-3">
<div class="card-header"><i class="fa fa-user"></i> Users</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-bordered table-striped table-compact" width="100%" id="userTable" cellspacing="0"></table>
</div>
</div>
</div>
</div>
</div>
[admin.blade.php] (Javascript)
<script type="text/javascript">
$(document).ready(function() {
$('#userTable').DataTable( {
"scrollX": true,
"scrollY": '55vh',
"scrollCollapse": true,
"paging": false,
dom: 'ft',
"aaData": "{{ $users }}",
"aoColumns": [
{ "sTitle": "Name", "mData": "name" },
{ "sTitle": "Email", "mData": "email" },
]
} );
} );
</script>
[Example JSON object/array returned from database]
array:1 [
0 => {#195
+"id": 1
+"name": "Josh_W"
+"email": "user#email.com"
+"group": "Admin"
+"level": 5
+"password": "PASSWORD"
+"remember_token": null
+"created_at": "2017-10-12 14:42:38"
+"updated_at": "2017-10-12 14:42:38"
}
]
The select() method returns an array. You need to collect() the array and then call toJson():
<script type="text/javascript">
$(document).ready(function() {
$('#userTable').DataTable( {
"scrollX": true,
"scrollY": '55vh',
"scrollCollapse": true,
"paging": false,
dom: 'ft',
"aaData": {!! collect($users)->toJson() !!},
"aoColumns": [
{ "sTitle": "Name", "mData": "name" },
{ "sTitle": "Email", "mData": "email" },
]
} );
} );
</script>
To avoid escaping your JSON use the {!! !!} syntax.
See the Laravel documentation on collections and displaying data on views for reference.

DataTables with AJAX - How to pass in a column hyperlink an external variable

I'm beginner in DataTables or dev in general :)
I use Laravel 5.4 and several DataTables which get their data using ajax calls requests and everything it's working just fine :) .
One of the tables have a column with a hyperlink on it I need to send further in the hyperlink an external variable which is not returned by Ajax response but it's hidden in same form with the table.
So, I have the table definition:
$('#tabelClientiOferta').DataTable({
lengthMenu: [[15, 25, 100, -1], [15,25, 100, "All"]],
processing: true,
serverSide: true,
ajax: 'ajaxClienti',
columns: [
{data:'id',name:'id' , sClass: "hidden", "bSearchable": false },
{data: 'denumire', name: 'denumire',
"fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
$(nTd).html("<a href='selectieFurnizor?idClient=" + oData.id + "'>" + oData.denumire + "</a>")
}
},
{ data: 'cui', name: 'cui' },
{ data: 'telefon', name: 'telefon', "bSearchable": false},
{ data: 'email', name: 'email', "bSearchable": false },
]
});
Controller function which respond to ajax call:
public function clienti(Request $request)
{
return Datatables::of(DB::table('clienti')->get(['id','denumire','cui','telefon','email']))->make(true);
}
HTML template with table and hidden variable:
#extends ('master')
#section('content')
<div class="container">
<div class="row">
<div class="col-sm-12">
<div class="tabelOferte" style ="width: 900px">
<table id = "tabelClientiOferta" class="table table-responsive table-striped table-hover">
<thead >
<tr style="font-weight: bold" >
<td>id</td>
<td>Denumire</td>
<td>CUI</td>
<td>Telefon</td>
<td>Email</td>
</tr>
</thead>
</table>
</div>
<input id = "hiddenId" name="hiddenId" type="text" value = {{$someId}} hidden />
</div>
</div>
</div>
#stop
So I need to pass the hidden variable as the second parameter to the "denumire" column hyperlink, something like:
$(nTd).html("<a href='selectieFurnizor?idClient=" + oData.id + "&hiddenId="+$('#hiddenId') "'>" + oData.denumire + "</a>")
.
Is that possible?
The solution which I use now is to return a view from the controller and include in it a static DataTable (with data already prepared and sent by the controller).
Thank you for your attention
:)
Server-side: use add coloumn from controller
$data = DB::table('clienti')->get(['id','denumire','cui','telefon','email']);
return Datatables::of($data)
->addColumn('clear', function ($data) {
return '<i class="glyphicon glyphicon-trash"></i> Clear';
})
->escapeColumns([])
->make(true);
And add to columns with initial js of datatables
{data: 'clear', name: 'cleat', orderable: false, searchable: false }
or use js based columns render() function, official doc and examples here: https://datatables.net/reference/option/columns.render

I am unable click on datatables row to send data to text field in Laravel 5.4

I have a web app in Laravel 5.4. In some modules, I have a main form from which datatables are called in a modal dialog window (for example: if I click on a search button, the modal window appears with the datatables in it).
What I am trying to achieve is that when I click on the data in the datatables it closes the modal window and get the clicked info and display it in a specified field in a form, the main form.
But after I put all the necessary scripts, nothing happens when I click on the data in the datatable.
a. HTML Table
<section class="panel">
<div class="table-responsive">
<table width="100%" id="pere-table" class="table" >
<thead>
<tr>
<th>NNID</th>
<th>Nom</th>
<th>Post-Nom</th>
<th>Prenom</th>
</tr>
</thead>
<tbody>
<tr >
<td class="NNID"></td>
<td class="nom"></td>
<td class="postnom"></td>
<td class="prenom"></td>
</tr>
</tbody>
</table>
</div>
</section>
<small><span class="glyphicon glyphicon-plus"></span> Ajouter</small>
b.Input Field to receive Data has pere_nouv as its id
Controller fetching the data
public function recherchePere ()
{
$pere = Pere::join('t_individus','t_adultes.nnid', '=',
't_individus.nnid')
->select(['t_individus.nom', 't_individus.postnom',
't_individus.prenom', 't_individus.nnid'])
->where('t_individus.sexe','=','0');
return Datatables::eloquent($pere)->make(true);
}
the ajax for the datatable
#push('scripts')
<script type="text/javascript">
$(function() {
$('#pere-table').DataTable({
processing: false,
serverSide: true,
ordering: false,
ajax:'http://127.0.0.1:8000/nouveau_ne/data_peres',
columns :[
{data : 'nnid', name:'t_individus.nnid'},
{data : 'nom', name:'t_individus.nom'},
{data : 'postnom', name:'t_individus.postnom'},
{data : 'prenom', name:'t_individus.prenom'},
]
});
});
</script>
#endpush
The route
Route::get('/nouveau_ne/data_peres', ['as' => 'nouveau_ne','uses' =>
'AdulteController#recherchePere']);
Route::get('/nouveau_ne/pere', [ 'uses' => 'AdulteController#index']);
The Jquery Script for Clicking on a row to feed a text box
<script type="text/javascript">
var vpWidth = $(window).width();
var vpHeight = $(window).height();
var textClickedOn;
var pereNouv = $("#pere_nouv");
var nnid = $(".NNID");
nnid.click(function(){
//Get text clicked on
textClickedOn = $(this).text();
//alert(textClickedOn);
pereNouv.val(textClickedOn);
});
</script>
QUESTION: What am I doing wrong? Your help and tips will be highly appreciated
Click event is attachted to existing elements on page load. The key word here is existing. When we load something with ajax we manipulate DOM. We are placing totally new element.
Delegated events have the advantage that they can process events from
descendant elements that are added to the document at a later time
try something like :
$('body').on('click', '#pere_nouv', function (event) {
// your code goes here
});
or this :
$(document).on('click','body #pere_nouv',function(){
// additional code
});

How to Render Api Data to Twig file using Angular js

what i need
i need to render data in symfony2 twig file.
some one has marked my question duplicate ,i need to render data using angular js not using symfony.
js code
function EntryCtrl ($scope, $http) {
$scope.rootEntry = [];
$http.get('https://api.github.com/users/mralexgray/repos').success(function(root) {
$scope.rootEntry = root;
console.log($scope.rootEntry);
});
}
output of variable $scope.rootEntry
data
{
id: 1,
name: "afeef",
price: "20",
description: "this is test page"
},
{
id: 2,
name: "afeef",
price: "20",
description: "this is test page"
}
html code
<body >
<div class="row" ng-controller="EntryCtrl">
<---updated code -->
# i have tried map model as well as
<table ng-model="rootEntry">
<div id="treeview" class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
<ul>
<li ng-repeat="root in rootEntry">{{root.name}}</li>
</ul>
</div>
</table>
</div>
Exception variable rootEntry is does not exists
controller code
public function checkAction()
{
$this->render('bundlename:twigfilename');
}
error rootentry doesnot exist
i need to show json data in twig file
solution
1. it can be done through symfony2 by rendering the json data through controller
like $this->render('bundlename:twigfilename',array('rootEntry,['jsonstring']);
but i need to make http request to send data in twig file
im new in angular js any suggestion is most welcome
general way for angular rendering
var mockDataForThisTest = "json=" + encodeURI(JSON.stringify([
{
id: 1,
firstName: "Peter",
lastName: "Jhons"},
{
id: 2,
firstName: "David",
lastName: "Bowie"}
]));
var app = angular.module('myApp', []);
function PeopleCtrl($scope, $http) {
$scope.people = [];
$scope.loadPeople = function() {
var httpRequest = $http({
method: 'POST',
url: '/echo/json/',
data: mockDataForThisTest
}).success(function(data, status) {
$scope.people = data;
});
};
}
html code
<div ng-app="myApp">
<div ng-controller="PeopleCtrl">
<p> Click <a ng-click="loadPeople()">here</a> to load data.</p>
<table>
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
<tr ng-repeat="person in people">
<td>{{person.id}}</td>
<td>{{person.firstName}}</td>
<td>{{person.lastName}}</td>
</tr>
</table>
</div>
</div>
but in this question how could i render data in twig through angular js.
You have to change angular's interpolation markup. In fact, twig is using the same interpolation markup as angular: "{{ }}" that's why you had that error: twig is expecting a variable defined in your symfony controller.
To do so, you have to configure your application module:
angular.module('myApp',[]).config(function($interpolateProvider){
$interpolateProvider.startSymbol('[[');
$interpolateProvider.endSymbol(']]');
}
Now, in your twig page use [[ ]] instead of {{ }}:
<div ng-app="myApp">
<div ng-controller="PeopleCtrl">
<p> Click <a ng-click="loadPeople()">here</a> to load data.</p>
<table>
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
<tr ng-repeat="person in people">
<td>[[person.id]]</td>
<td>[[person.firstName]]</td>
<td>[[person.lastName]]</td>
</tr>
</table>
</div>
I hope this will help you :)
P.S: for resolving $http promises use then instead of succes (it is deprecated)
https://docs.angularjs.org/api/ng/service/$http#deprecation-notice
For people with this problem in the future: you can use {% verbatim %}. It tells Twig to not process the code inside.
In the next code you have how to get Twig and Angular working together.
{{ max(1, 3, 2) }} <<< The render is done by Twig
{% verbatim %}
<div ng-app="">
<p>Name : <input type="text" ng-model="name"></p>
Hello {{name}} <<< The render is done by Angular
</div>
{% endverbatim %}
More info in https://ourcodeworld.com/articles/read/215/how-to-use-angular-js-and-twig-without-the-conflict-of-double-curly-braces

Categories