I am using Yajra's DataTables server side processing. I can see the JSON data but the table is not being populated.
I managed to get DataTables working with client side processing, but as I will eventually have > 50,000 rows of data, I decided to try and implement server side processing by downloading Yajra's DataTables for Laravel 5.8.
When I call my route, I see the data in a JSON format, but I am not seeing the table at all. It says "draw: 0", so I guess there is an issue with drawing the table?
I have tried various solutions mentioned on stack overflow and the official DataTables website, however none seem to work for me. E.g.
- DataTables json is not processed (in Laravel)
- jQuery Datatables - Table not populated for Ajax response
- https://datatables.net/forums/discussion/45444/populate-table-body-with-ajax
The JSON data that I see when I call my route is as follows:
{
"draw": 0,
"recordsTotal": 3,
"recordsFiltered": 3,
"data": [
{
"id": "1",
"customerNr": "98764",
"orderNr": "23478",
"pallet_id": "66788",
"status_id": "2",
"created_by": "Sara",
"created_at": "04 Jul 2019",
"updated_at": "2019-07-09 07:23:20"
},
{
"id": "2",
"customerNr": "99999",
"orderNr": "22222",
"pallet_id": "22335",
"status_id": "1",
"created_by": "Sophie",
"created_at": "04 Jul 2019",
"updated_at": "2019-07-04 08:26:28"
},
{
"id": "3",
"customerNr": "54657",
"orderNr": "89856",
"pallet_id": "11228",
"status_id": "1",
"created_by": "Markus",
"created_at": "08 Jul 2019",
"updated_at": "2019-07-08 06:59:42"
},
],
"input": []
}
Here are the relevant files from my Laravel project:
web.php:
Route::get('returned-shipment', ['uses'=>'ReturnedShipmentController#index', 'as'=>'returned-shipment.index']);
ReturnedShipmentController:
public function index(
{
return DataTables::of(ReturnedShipment::all())->make();
}
index.blade.php:
<div class="row">
<div id="tbl" class="col-sm-12">
<table id="overview" class="cell-border display">
<thead class="tbl-top">
<tr>
<th>Retourennummer</th>
<th>Auftragsnummer</th>
<th>Datum</th>
<th>Zustand</th>
</tr>
</thead>
<tfoot class="tbl-bottom">
<tr>
<th>Retourennummer</th>
<th>Auftragsnummer</th>
<th>Datum</th>
<th>Zustand</th>
</tr>
</tfoot>
</table>
</div>
</div>
<script>
$(document).ready(function () {
var startingStatus = 'angelegt';
var table = $('#overview').DataTable({
"processing": true,
"serverSide": true,
"ajax": "{{ route('returned-shipment.index') }}",
"columns": [
{data: 'id'},
{data: 'orderNr'},
{data: 'created_at'},
{data: 'status_id'}
],
"search": {
"search": "angelegt"
},
"dom": "<'row'<'col-sm-4'l><'col-sm-8'f>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-6'i><'col-sm-6'p>>",
"paging": true,
"info": true,
"searching": true,
"autoWidth": true,
"language": {
"paginate": {
"previous": "Vorherige Seite",
"next": "Nächste Seite"
},
"search": "Suche:",
"info": "Zeige _START_ - _END_ von insgesamt _TOTAL_ Einträgen",
"lengthMenu": 'Einträge pro Seite' + '<br>' +
'<select class="custom-select mr-sm-2" id="inlineFormCustomSelect">' +
'<option selected value="10">10</option>' +
'<option value="20">20</option>' +
'<option value="30">30</option>' +
'<option value="40">40</option>' +
'<option value="50">50</option>' +
'<option value="-1">Alle</option>' +
'</select>'
},
initComplete: function () {
/**
* Drop-down filter is created for the 4th column "status" in the header and populates it with
* the different status values
*/
this.api().columns([3]).every(function () {
var column = this;
var select = $('<select><option value="">alle</option></select>')
.appendTo($(column.header()))
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search(val ? '^' + val + '$' : '', true, false)
.draw();
});
/**
* When clicking on drop-down next to status, the sorting function is not activated
*/
$(select).click(function (e) {
e.stopPropagation();
});
/**
* Once an option in the drop-down next to status has been selected, you can read the text in
* the drop-down
*/
column.data().unique().sort().each(function (d, j) {
if (startingStatus === d) {
select.append('<option SELECTED value="' + d + '">' + d + '</option>')
} else {
select.append('<option value="' + d + '">' + d + '</option>')
}
});
/**
* When drop-down is clicked on, search field is cleared. Otherwise search field must be
* manually cleared before using the drop-down.
*/
$(select).on('click', function () {
table.search(" ").draw();
});
});
}
});
});
</script>
I am expecting to see the table being populated with the data.
If I need to provide any more code or explain something further, please don't hesitate to ask. I am quite new to Laravel and DataTables, so I would greatly appreciate your help.
Thanks in advance! :)
I have checked your current code and checked your JSON. Your JSON file seems to be invalid.
{
"draw": 0,
"recordsTotal": 3,
"recordsFiltered": 3,
"data": [
{
"id": "1",
"customerNr": "98764",
"orderNr": "23478",
"pallet_id": "66788",
"status_id": "2",
"created_by": "Sara",
"created_at": "04 Jul 2019",
"updated_at": "2019-07-09 07:23:20"
},
{
"id": "2",
"customerNr": "99999",
"orderNr": "22222",
"pallet_id": "22335",
"status_id": "1",
"created_by": "Sophie",
"created_at": "04 Jul 2019",
"updated_at": "2019-07-04 08:26:28"
},
{
"id": "3",
"customerNr": "54657",
"orderNr": "89856",
"pallet_id": "11228",
"status_id": "1",
"created_by": "Markus",
"created_at": "08 Jul 2019",
"updated_at": "2019-07-08 06:59:42"
}
],
"input": []
}
This is the correct format. The comma after the last object in your data array needs to be removed. Can you confirm this solves your issue? I got datatables working without this comma.
Related
I am mounting a table and perfect until I want to show more data, I have read that I can use server side but I have not found any example how to consume an web service that returns json
html
<table id="datatable-buscador" class="display nowrap" style="width:100%">
<thead>
<tr>
<th>Nº reco.</th>
<th>Fecha</th>
<th>Id trabajador</th>
<th>Trabajador</th>
<th>Id empresa</th>
<th>Ref. Int.</th>
<th>Nombre empresa</th>
<th>Visado</th>
<th>Prop.</th>
</tr>
</thead>
</table>
javascript
let $tabla = jQuery("#datatable-buscador");
$tabla.dataTable().fnDestroy();
$tabla.dataTable({
"scrollX": true,
"lengthMenu": [[15, 25, 30, -1], [15, 25, 30, "All"]],
"lengthChange": false,
"order": [1, "desc"], //columna 0 y ordenar desc
"language": { "url": "/src_reconocimientos/includes/js/utils/spanish.json" },
"ajax": {
url: "/example/example.php",
type: "POST",
dataType: "JSON",
data: { "tipo": tipo, "dias_reco": diasReco },
timeout: 180000 //3 min
},
"createdRow": function (row, data, dataIndex) {
jQuery(row).attr("id", data.N_RECONOCIMIENTO);
},
"columnDefs": [
{
// targets: "_all",
targets: [0, 1, 2, 4, 5, 7, 8],
className: 'dt-body-center'
},
],
"columns": [
{ "data": "N_RECONOCIMIENTO" },// 0
{
"data": null,
render: function (data, type, full, meta) {
return formatFecha(data.FECHA_RECONOCIMIENTO);
}
}, //1
{ "data": "DNI" }, // 2
{ "data": "NOMBRE_TRABAJADOR" }, // 3
{ "data": "EMPRESA" }, // 4
{ "data": "REF_INTERNA" }, // 5
{ "data": "NOMBRE_CLIENTE" }, // 6
{ "data": "VISADO" }, // 7
{ "data": "PROP" }, // 8
]
});
json:
{
"data": [{
"N_RECONOCIMIENTO": 29457,
"FECHA_RECONOCIMIENTO": "2021-10-11",
"DNI": "28460Q",
"NOMBRE_TRABAJADOR": "CAMPS",
"EMPRESA": 112390,
"REF_INTERNA": "Ref_interna?",
"NOMBRE_CLIENTE": "example",
"VISADO": "N",
"PROP": "Prop?"
}, {
"N_RECONOCIMIENTO": 2907,
"FECHA_RECONOCIMIENTO": "2021-10-14",
"DNI": "414J",
"NOMBRE_TRABAJADOR": "CARLOS",
"EMPRESA": 103482,
"REF_INTERNA": "Ref_interna?",
"NOMBRE_CLIENTE": "(ACUERDO DE COLABORA)",
"VISADO": "N",
"PROP": "Prop?"
}, {
"N_RECONOCIMIENTO": 2619,
"FECHA_RECONOCIMIENTO": "2021-04-16",
"DNI": "72306W",
"NOMBRE_TRABAJADOR": "DIEZ",
"EMPRESA": 29514,
"REF_INTERNA": "Ref_interna?",
"NOMBRE_CLIENTE": "example 365, S.L.",
"VISADO": "S",
"PROP": "Prop?"
}]
}
when pointing to the url of the ajax what it returns me is a json that changes the content according to the data that I pass to it, but when I want to get more 50000 records, the table fails me, so I want to implement serverside, how can I implement it and keep pointing the same url? I don't see anything related in the datatables examples
add info:
It is a very simple company webservice that receives data through my php script with cURL, in this it receives a type of request (it can be 1, 2, 3) and receives parameters (variables), the web services does the queries, simple queries and returns the result as json, it cannot be interacted any more, that's why when I try to process 50000 the datatable gives me an error. my question is: how can I do an intermediate step to process so many lines?
when we pass static list of data like [{category":"a","data:"3"},"category":"b","data":"1"}]
then its working fine, but when we pass page url like {"url": "abc.php","format": "json"} in dataprovider section then chart not populate.
This is my code:
var chart = AmCharts.makeChart("chartdiv", {
"type": "pie",
"dataProvider":{ "
url": "abc.php",
"format": "json" },
"labelRadius": -35,
"labelText": "[[percents]]%",
"titleField": "category",
"valueField": "column-1",
"allLabels": [],
"balloon": {},
"legend": {
"enabled": true,
"align": "center",
"markerType": "circle" }
});
Any solution?
Using amCharts with "static" data
If you have "static" data, use the dataProvider setting, like this:
var chart = AmCharts.makeChart("chartdiv", {
"type": "pie",
"dataProvider": [{
"category": "a",
"data": 3
}, {
"category": "b",
"data": 1
}],
// ...
});
Using amCharts with AJAX data
If you want the data to be loaded using AJAX, one way is to make use of amCharts' Data Loader plugin.
Make sure to include it in your HTML:
<script src="amcharts/plugins/dataloader/dataloader.min.js" type="text/javascript"></script>
Leave out the dataProvider setting, and use dataLoader instead.
var chart = AmCharts.makeChart( "chartdiv", {
"type": "pie",
"dataLoader": {
"url": "abc.php",
"format": "json"
},
// ...
});
Your abc.php file should return valid JSON, like this:
[{
"category": "a",
"data": 3
}, {
"category": "b",
"data": 1
}]
You can find a complete list of options for the Data Loader plugin here: https://www.amcharts.com/kbase/using-data-loader-plugin/.
Does anyone know how to filter the posts shown on fullcalendar based on their custom fields?
Example: If I wanted to only show "media == twitter" how would I be able to accomplish this using only one json feed?
I appreciate any ideas.
Example of Json:
{
"id": "1",
"title": "Title",
"description": "Details",
"media": "twitter",
},
{
"id": "2",
"title": "Title",
"description": "Details",
"media": "linkedin",
},
{
"id": "3",
"title": "Title",
"description": "Details",
"media": "facebook",
}
The following is the basic setup I have so far of the fullcalendar which is currently working fine.
Example of FullCalendar code:
$(document).ready(function() {
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
defaultDate: '<? echo '2015-11-01'; ?>',
editable: false,
events: "json.php",
eventClick: function(event) {
if (event.url) {
window.open('#' + event.id,"_self");
return false;
}
}
});
According to above mentioned description as a solution to filter json feed,you need to decode json data into php associative array using json_decode() function and apply filter for specific data while iterating over an associative array.
Please refer the example code snippet to filter json data
<?php $json_data='[
{
"id": "1",
"title": "Title",
"description": "Details",
"media": "twitter"
},
{
"id": "2",
"title": "Title",
"description": "Details",
"media": "linkedin"
},
{
"id": "3",
"title": "Title",
"description": "Details",
"media": "facebook"
}
]';
$result=NULL;
$json_array=json_decode($json_data,true);
if($json_array)
{
foreach($json_array as $json)
{
switch($json['media'])
{
case 'twitter':
$result=$json;
break;
}
}
}
echo json_encode($result);
?>
$result variable will hold the filtered json data.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Please view my other question here
I am trying to work out how to decode a JSON response from a PHP file.
The JSON is structured as follows:
[{
"id": 1,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/amazon-webstore-379672",
"price": " - "
}
}, {
"id": 2,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/we-need-someone-to-design-t-shirts-for-the-world-cup-2014-379671",
"price": "\u00a3 50 "
}
}, {
"id": 3,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/unusual-request-for-expert-help-to-work-on-lowering-google-p-379670",
"price": "\u00a3 50 "
}
}, {
"id": 4,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/1-to-2-developers-to-work-on-a-large-project-379669",
"price": " - "
}
}, {
"id": 5,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/we-would-like-someone-to-design-some-world-cup-t-shirts-for-379665",
"price": "\u00a3 50 "
}
}, {
"id": 6,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/graphic-design-of-3-x-sample-pages-for-a-website-379664",
"price": "\u00a3 200 "
}
}, {
"id": 7,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/youtube-channel-art-379663",
"price": "\u00a3 9 "
}
}, {
"id": 8,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/pr-events-organisation-source-prizes-for-charity-raffle-379661",
"price": "\u00a3 100 "
}
}, {
"id": 9,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/wordpress-thesis-website-finessing-improve-main-opt-in-des-379659",
"price": "\u00a3 40 "
}
}, {
"id": 10,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/i-would-like-my-logo-redesigned-updated-379651",
"price": "\u00a3 10 "
}
}, {
"id": 11,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/pattern-maker-pattern-cutter-379650",
"price": " - "
}
}, {
"id": 12,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/add-captcha-379652",
"price": "\u00a3 30 "
}
}, {
"id": 13,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/setup-salesforce-api-so-we-can-just-pull-data-via-rest-379638",
"price": "\u00a3 31 "
}
}, {
"id": 14,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/simple-map-illustration-379643",
"price": "\u00a3 25 "
}
}, {
"id": 15,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/time-lapse-video-for-indoor-construction-project-12-week-p-379637",
"price": "\u00a3 1.0k "
}
}, {
"id": 16,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/i-need-a-asterisk-vicidial-expert-to-help-support-us-379640",
"price": "\u00a3 15 "
}
}, {
"id": 17,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/i-need-a-freelancer-to-provide-help-setting-up-cytoscape-379641",
"price": "\u00a3 21 \/hr"
}
}, {
"id": 18,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/500-word-article-on-business-today-379632",
"price": "\u00a3 12 "
}
}, {
"id": 19,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/web-interface-app-design-379629",
"price": "\u00a3 20 \/hr"
}
}, {
"id": 20,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/distribute-leaflets-in-central-birmingham-379630",
"price": "\u00a3 7 \/hr"
}
}]
You can view the current AJAX call on my other question (Link at top of this post).
Could anyone shed some light on how I would decode the JSON array client-side?
I'd like to have a structure like this:
<div class="item">
<div class="title">JSON Title</div>
<div class="price">JSON Price</div>
</div>
Note : from your other question, it is not clear if you always expect a json answer, or if you can receive either of json, html, or xml.
If you always expect json :
$.ajax({ url: ..., data: ...,
dataType: 'json', // <- tell jQuery to expect json,
// and to build a js object from the answer
success : function(obj){
//obj is a regular js object, built from the received json
obj[i].info.title; // <- accessing this piece of data
}
});
If your data is sometimes json, sometimes something else :
success: function(data){
var obj
try {
obj = JSON.parse(data);
// if no exception is thrown, data was a valid json string,
// and obj is a regular js object
obj[i].info.title; // <- accessing this piece of data
} catch (e) {
// Maybe do something on error ?
};
}
You can then build a html string like hsuk suggested :
var html = '';
for(i=0; i < obj.length; i++) {
html += '<div class="item">';
html += '<div class="title">' + obj[i].info.title + '</div>';
html += '<div class="price">' + obj[i].info.price + '</div>';
html += '</div>';
}
alert.html(html).fadeIn();
This is how you do it. What you need is JSON.parse()
test.php
<?php
// Ajax-Server Request Handler
if (isset($_GET['loadData'])) {
exit(json_encode(array(
array(
'id' => 1,
'info' => array('title' => 'http://www.peopleperhour.com/job/amazon-webstore-379672', 'price' => ' - ')
),
array(
'id' => 2,
'info' => array('title' => 'http://www.peopleperhour.com/job/we-need-someone-to-design-t-shirts-for-the-world-cup-2014-379671', 'price' => '\u00a3 50 ')
),
array(
'id' => 3,
'info' => array('title' => 'http://www.peopleperhour.com/job/unusual-request-for-expert-help-to-work-on-lowering-google-p-379670', 'price' => '\u00a3 50 ')
)
)));
}
?>
<!-- Ajax-Client -->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
// When Page Loads
$(document).ready(function()
{
// Make Ajax Request
$.get("test.php?loadData", function(data)
{
// Parse Data
var jsonResults = JSON.parse(data);
// Iterate Through Results
$.each(jsonResults, function(key, value)
{
// Display Data
$('.results').append(
'<div class="item" id="'+ value.info.id +'">'+
'<div class="title">'+ value.info.title +'</div>'+
'<div class="price">'+ value.info.price +'</div>'+
'</div>'
);
});
});
});
</script>
<!-- HTML Page - Display Result -->
<div class="results"></div>
Actually, the funny bit about JSON (JavaScript Object Notation) is that you can use it as is in Javascript.
Meaning, if your JSON string is {"foo": "bar"}, you can directly use it in Javascript like:
var myObject = {"foo": "bar"};
or
var myJSONString = '{"foo": "bar"}';
var myObject = eval(myJSONString);
But maybe you better go with JSON.Parse , as eval might be vulnerability if you are parsing User Data, that might not necessarily be in JSON format. (EG. Json data that is sent via HTTP, where the client could mess with ti.)
I have this JSON string in a PHP page:
{
"elements": [{
"type": "pie",
"alpha": 0.3,
"animate": [{
"type": "fade"
}, {
"type": "bounce",
"distance": 5
}],
"start-angle": 0,
"tip": "#val# de #total# #percent#",
"colours": ["#d01f3c", "#356aa0", "#C79810"],
"values": [{
"value": 1,
"label": "procesador amd sempron 140"
}, {
"value": 1,
"label": "procesador sempron le130"
}, {
"value": 1,
"label": "procesador amd a4-3300 x2"
}, {
"value": 1,
"label": "procesador intel celeron g530"
}]
}],
"title": {
"text": "Procesadores, Reinicio",
"style": "color: #356aa0; font-size: 20px"
},
"bg_colour": "#FFFFFF",
"x_axis": null
}
I call it like this:
$.getJSON("restart_proce.php", function(json)
{
console.log(json);
I need to transform it to this:
[{\"value\": 1, \"label\": \"procesador amd sempron 140\" }, { \"value\": 1, \"label\": \"procesador sempron le130\" }, { \"value\": 1, \"label\": \"procesador amd a4-3300 x2\" }, { \"value\": 1, \"label\": \"procesador intel celeron g530\" } ]
I'm trying to delete elements like this:
delete json.elements[3];
but it doesn't delete anything. How can I make it work?
Removing an item from an Array:
There are several ways. The splice method is the most versatile:
data.items.splice(3, 1); // Removes three items starting with the 2nd,
splice modifies the original array, and returns an array of the items you removed.
Try this:
json.elements.splice(3, 1);
See: Array.splice
Just modify the values directly before console.log(json)
json= json.elements[0].values
Or in the restart_proce.php php page just echo
echo json_encode($data['elements'][0]['values']); // if associative array is used.
Try this:
var data = {"result":[
{"FirstName":"Test1","LastName":"User","Email":"test#test.com","City":"ahmedabad","State":"sk","Country":"canada","Status":"False","iUserID":"23"},
{"FirstName":"user","LastName":"user","Email":"u#u.com","City":"ahmedabad","State":"Gujarat","Country":"India","Status":"True","iUserID":"41"},
{"FirstName":"Ropbert","LastName":"Jones","Email":"Robert#gmail.com","City":"NewYork","State":"gfg","Country":"fgdfgdfg","Status":"True","iUserID":"48"},
{"FirstName":"hitesh","LastName":"prajapti","Email":"hitesh.prajapati#phptalent.com","City":"","State":"","Country":"","Status":"True","iUserID":"78"}
]
}
alert(data.result);
delete data.result[3];
alert(data.result);
working JSFiddle
or You can use splice to remove elements from an array.