DataTable Populate Ajax - json

I have a datatable js and I fill in with ajax (json), in my json, its return is several entries, I see this through the console, but, the datatable is only populated with the first json record.
My Code
$(document).ready(function()
{
$.ajax({
type : 'POST',
url : 'view/list/clients_1.php',
dataType: 'json',
cache: false,
success : function(result)
{
//pass data to datatable
console.log(result); // just to see I'm getting the correct data.
$('#my_table').DataTable({
"searching": false, //this is disabled because I have a custom search.
"bAutoWidth": false,
"bFilter": true,
"bLengthChange": false,
"responsive": true,
"aaData": [result], //here we get the array data from the ajax call.
"aoColumns": [
{ "sTitle": "#" },
{ "sTitle": "Name" },
{ "sTitle": "Work" }
]
});
}
});
Code of file: clients_1.php
$clients_sql =
"
SELECT
*
FROM
client
";
$result = mysqli_query($mysqli, $clients_sql);
$dataArray = array();
while( $row = mysqli_fetch_array($result) )
{
$dataArray[] = $row["client_id"];
$dataArray[] = $row["client_name"];
$dataArray[] = $row["client_work"];
}
echo json_encode($dataArray);

resolved
var table = $('#my_table').dataTable({
serverSide: true,
searching: false,
bAutoWidth:false,
bFilter: true,
bLengthChange: false,
responsive: true,
ajax: "view/lista/clientes_1.php",
dataSrc: 'data',
columns: [
{sTitle: "#", data: 'client_id' },
{sTitle: "Name", data: 'client_nome' },
{sTitle: "Work", data: 'client_work' }
]
}); // End: DataTable
$('#search-table').unbind();
$('#search-table').bind('keyup', function(e) {
//if(e.keyCode == 13) {
table.fnFilter(this.value);
// }
});
PHP
$result = mysqli_query($mysqli, $clients_sql);
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
$data[] = $row;
}
$results = [
"sEcho" => 1,
"iTotalRecords" => count($data),
"iTotalDisplayRecords" => count($data),
"aaData" => $data
];
echo json_encode($results);

I recommend adding to the answer given by sNniffer
$data = [];
just above the while loop.
Otherwise, when there are no rows in the query (and the while loop is not executed), you get this warning from datatables

Related

How To generate json format from model in codeigniter

I Have Database :
enter image description here
how to query mysql in codeigniter model so that it can output json data like this :
enter code here</script">
$.ajax({
url: '?grid=true&tahun=' + tahuncikarang,
method: "GET",
success: function(data) {
var obj = JSON.parse(data);
}
Highcharts.chart('cikarang', {
chart: {
type: 'bar'
},
title: {
text: 'Highcharts multi-series drilldown'
},
subtitle: {
text: 'The <em>allowPointDrilldown</em> option makes point clicks drill to the whole category'
},
xAxis: {
type: 'category'
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: true
}
}
},
series: [{
name: '2010',
data: obj.tahun1
}, {
name: '2014',
data: obj.tahun2
}],
drilldown: {
allowPointDrilldown: false,
series: [{
id: 'republican-2010',
name: 'Republican 2010',
data: [
['East', 4],
['West', 2],
['North', 1],
['South', 4]
]
}, {
id: 'democrats-2010',
name: 'Republican 2010',
data: ''
}, ]
}
});
}
});
I try in model :
function index($tahuncikarang)
{
$this->db->select('nama AS nama, CONCAT(nama,"-", tahun) AS drilldown, sum(nilai) AS y');
$this->db->where('tahun=2010');
$this->db->group_by('nama')
->group_by('tahun');
$tahuna1 = $this->db->get(self::$table5);
$tahuna2 = array();
foreach ($tahuna1->result() as $row) {
array_push($tahuna2, $row);
}
$this->db->select('nama AS nama, CONCAT(nama,"-", tahun) AS drilldown, sum(nilai) AS y');
$this->db->where('tahun=2014');
$this->db->group_by('nama')
->group_by('tahun');
$tahunb1 = $this->db->get(self::$table5);
$tahunb2 = array();
foreach ($tahunb1->result() as $row) {
array_push($tahunb2, $row);
}
$result = array();
$result['tahun1'] = $tahuna2;
$result['tahun2'] = $tahunb2;
return json_encode($result, JSON_NUMERIC_CHECK);
}
I read your question just before.
If you could use this query, you maybe get good results.
Thank you
$qy = $this->db->query("select concat(lower(nama),'-',tahun) as id,concat(nama,'-',tahun) as name,group_concat(concat(zone,'-' ,nilai),',') as data group by nama, tahun")->result_array();
$result = array();
foreach($qy as $row) {
$temp = array(
"id"=>$row['id'],
"name"=>$row['name'],
"data"=>array()
);
$array = explode(',',$row['data']);
foreach($array as $el) {
$temp['data'][]=explode('-',$el);
}
$result[] = $temp;
}
echo json_encode($result);

How to get json data after redraw of datatable?

When page load for the first time, I got json object returned from controller. But after deletion of a data it doesn't return json object. I mean, I can access requestTable.ajax.json() after initial load of var requestTable = $('#Request-Table').DataTable({});. But after any event when the table got redrawn, requestTable.ajax.json() gives an error.
My main concern is how to get value of recordsTotal from json object after every event. Can anyone assist me with that?
Routes:
Route::group(['prefix' => '/requests'], function () {
Route::get('/show', [
'uses' => 'InvitationController#show',
'as' => 'requests.show',
]);
Route::delete('/delete/{id}', [
'uses' => 'InvitationController#destroy',
'as' => 'requests.destroy',
]);
});
Controller:
public function show()
{
return Datatables::of(Invitation::query()->whereNull('invitation_token'))->make(true);
}
public function destroy($id)
{
$invitations = Invitation::where('id', $id)->delete();
return Response::json($invitations);
}
DataTable Function:
// Initial Load
requestTable = $('#Request-Table').DataTable({
processing: true,
serverSide: true,
order: [[ 3, "asc" ]],
pagingType: "full_numbers",
ajax: '{{ route('requests.show') }}',
columns: [
{ data: 'id', name: 'id' },
{ data: 'email', name: 'email' },
{ data: 'created_at', name: 'created_at' },
],
columnDefs: [
{
targets: 0,
visible: false,
searchable: false
},
{
targets: 3,
render: function(data, type, row, meta){
return "<button type=\"button\" class=\"delete-request btn btn-sm btn-danger\" data-toggle=\"modal\" data-target=\"#Modal-Request-Delete\" data-id=\""+row.id+"\">Delete Request</button>";
},
searchable: false,
orderable: false
}
]
});
});
// Delete Request
$('body').on('click', '#Btn-Delete-Request', function () {
var requestId = $("#Delete-Request").data("id");
$("#Delete-Request").prop('id', '');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "delete",
url: "/requests/delete/"+requestId,
success: function (data) {
window.requestTable = $('#Request-Table').dataTable();
window.requestTable.fnDraw();
},
error: function (data) {
console.log('Error:', data);
}
});
});
Don't need to send data from delete you can just refresh your table by ajax.reload() function
below i put your code with modify check it's working or not
// Initial Load
var requestTable ;
requestTable = $('#Request-Table').DataTable({
processing: true,
serverSide: true,
order: [[ 3, "asc" ]],
pagingType: "full_numbers",
ajax: '{{ route('requests.show') }}',
columns: [
{ data: 'id', name: 'id' },
{ data: 'email', name: 'email' },
{ data: 'created_at', name: 'created_at' },
],
columnDefs: [
{
targets: 0,
visible: false,
searchable: false
},
{
targets: 3,
render: function(data, type, row, meta){
return "<button type=\"button\" class=\"delete-request btn btn-sm btn-danger\" data-toggle=\"modal\" data-target=\"#Modal-Request-Delete\" data-id=\""+row.id+"\">Delete Request</button>";
},
searchable: false,
orderable: false
}
]
});
});
// Delete Request
$('body').on('click', '#Btn-Delete-Request', function () {
var requestId = $("#Delete-Request").data("id");
$("#Delete-Request").prop('id', '');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "delete",
url: "/requests/delete/"+requestId,
success: function (data) {
requestTable.ajax.reload();
},
error: function (data) {
console.log('Error:', data);
}
});
});
above var requestTable so in delete function you can access that and requestTable.ajax.reload(); this function you can use to refresh you table

How to fix SyntaxError: Unexpected token &

I am sending a php coded in accordance with the json_encode function to a plantilla.twig where I want to graph a pie chart type and the browser shows me the following error in console uncaught SyntaxError: Unexpected token & ¨ and I red the line following data: [[& quot; Intermediate 17.5 inches & quot;, 2220]]
Controller Class
public function tiempoXEtapaAction()
{
$em = $this->getDoctrine()->getManager();
$servicepozo = $this->get('service.pozo');
$pozoActual = $servicepozo->getPozoActual();
$idpozo = $servicepozo->getPozoActual()->getId();
$activityCollections = $em->getRepository('ActividadBundle:ActividadDiariaCollection')->findBy(array('pozo' => $idpozo), array('id' => 'ASC'));
$intervalos = $em->getRepository('IntervaloBundle:Intervalo')->findBy(array('pozo' => $idpozo), array('id' => 'ASC'));
$actividades = $em->getRepository('ActividadBundle:ActividadDiaria')->findBy(array('pozo' => $idpozo), array('id' => 'ASC'));
$tiempoXIntervalo = array();
foreach ($activityCollections as $activityCollection) //Dias
{
$fechaActCole = $activityCollection->getFecha();
foreach ($intervalos as $intervalo) //Intervalos
{
if ($intervalo->getFechaInicio() <= $fechaActCole && $intervalo->getFechaFinal() >= $fechaActCole) {
$temp = array();
$temp[] = $intervalo.'';
foreach ($actividades as $actividad) //Actividades
{
if ($actividad->getCollection()->getId() == $activityCollection->getId()) {
$duracion[] = $actividad->getDuracion();
}
}
$temp[] = array_sum($duracion);
}
}
$tiempoXIntervalo[] = $temp;
}
return array('tiempoXIntervalo'=> (json_encode($tiempoXIntervalo)));
Template.Twig
title: {
text: 'Distribución de tiempo por Intervalo'
},
xAxis: {
reversed: false,
title: {
enabled: true,
text: 'Dias'
},
labels: {
formatter: function () {
return this.value;
}
},
maxPadding: 0.05,
showLastLabel: true,
allowDecimals: false,
min:0,
},
yAxis: {
max:0,
startOnTick: false,
title: {
text: 'Profundidad [m]'
},
labels: {
formatter: function () {
return this.value;
}
},
lineWidth: 2,
},
legend: {
enabled: true
},
tooltip: {
pointFormat: '{series.name}: <b>{point.y}h ({point.percentage:.1f}%)</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
showInLegend: true
}
},
series: [{
data:{{tiempoXIntervalo}}
}]
});
});
</script>
You should check how to convert HTML entities
Also, there is an extra space in & quot;
It should be "
json_encode expects " so it should be ["Intermediate 17.5 inches",2220]
Thanks Fernando but your solution do not work for mi.
Apparently the problem was Twig autoescaping variables. I tried to use Twig's raw filter to skip autoescaping and it's work for mi. Here the solution
data: $.parseJSON('{{ tiempoXIntervalo | raw }}')

passsing data to https by JSON using JSONP

i had try many diffrent tutarials and examples from http://api.jquery.com/jQuery.getJSON/ and Post data to JsonP and saw many staffs about how to convert json data to jasonP but still i can not do it,is there any one could see how should i pass my data over https within my codes here which i am using highcharts to get data from my domain sql server which is in diffrent server than my webpages host.here is my codes:(i know which i should use ajax request but i dont know how in my case,if anyone know please HELP!) tnx.
getting data by getJASON over data.php which request from sql server to grab data:
var Options;
$(document).ready(function() {
Options = {
chart: {
renderTo: 'container2',
type: 'area',
borderColor: "#3366ff",
borderWidth:5,
zoomType : 'x'
},
title: {
text: 'Total Meeting_Logs Duration of Organization1 '
},
subtitle: {
text: ' '
},
credits:{
enabled:false
},
xAxis: {
categories: [],
labels: {
align: 'center',
x: -3,
y: 20,
//format data based on #datepicker which is html jquery ui date
//picker
formatter: function() {
return Highcharts.dateFormat('%l%p',
Date.parse(this.value +' UTC'));
}
}
},
yAxis: {
title: {
text: ''
}
},
tooltip: {
backgroundColor: '#FCFFC5',
borderColor: 'black',
borderRadius: 10,
borderWidth: 3
},
// Enable for both axes
tooltip: {
crosshairs: [true,true]
},
plotOptions: {
line: {
dataLabels: {
enabled: true
},
enableMouseTracking: false
}
},
series: [{
type: 'area',
name: '',
data: []
}]
}
// here i get my data from data.php within same server
$.getJSON("data.php", function(json){
Options.xAxis.categories = json['category'];
Options.series[0].name = json['name'];
Options.series[0].data = json['data'];
chart = new Highcharts.Chart(Options);
});
});
//this function get user request for input time period and
//update in my domain
$(function() {
$( "#datepicker2" ).datepicker({
dateFormat: "yy-mm-dd",
showOn: "button",
buttonImage: "calendar.gif",
buttonImageOnly: true,
onSelect: function(dateText, inst) {
$.getJSON("data.php?dateparam1="+dateText, function(json){
Options.xAxis.categories = json['category'];
Options.series[0].name = json['name'];
Options.series[0].data = json['data'];
chart = new Highcharts.Chart(Options);
});
}
});
});
data.php:
`
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("moh1368_Mrs_Lemoine", $con);
if (isset($_GET["dateparam"])) {
$sql = mysql_query("SELECT timestamp_value, traffic_count FROM
foot_traffic WHERE timestamp_value LIKE '".$_GET["dateparam"]."%'");
} else {
$sql = mysql_query("SELECT timestamp_value, traffic_count FROM
foot_traffic WHERE timestamp_value LIKE '2013-02-01%'");
}
$result['name'] = 'Foot Traffic Count';
while($r = mysql_fetch_array($sql)) {
$datetime = $r['timestamp_value'];
$result['category'][] = $datetime;
$result['data'][] = $r['traffic_count'];
}
print json_encode($result, JSON_NUMERIC_CHECK);
mysql_close($con);
?>`

jqGrid returns blank cells

Can't seem to get the following jqGrid code to work http://cablegate.politicswiki.ie/stackoverflow.html
<script type="text/javascript">
$(document).ready(function(){
jQuery("#list2").jqGrid({
url:'http://tables.googlelabs.com/api/query?sql=SELECT * FROM 333136 LIMIT 10&jsonCallback=?',
datatype: "json",
colModel:[
{name:'ident',index:'ident',label:'ident', width:55},
{name:'date',index:'date',label:'date', width:90},
{name:'sourceId',index:'sourceId',label:'sourceId', width:100},
{name:'source',index:'source',label:'source', width:80},
{name:'tags',index:'tags',label:'tags', width:200}
],
jsonReader: {
repeatitems: false,
root: function (obj) {
var rows = new Array();
for(var i = 0; i < obj.table.rows.length;i++)
{
var row = new Object();
row.id = obj.table.rows[i][0];
row.cell = obj.table.rows[i];
rows[i] = row;
}
return rows;
},
page: function (obj) { return 1; },
total: function (obj) { return 1; },
records: function (obj) { return obj.table.rows.length; }
},
rowNum:10,
rowList:[10,20,30],
pager: '#pager2',
sortname: 'id',
viewrecords: true,
sortorder: "desc",
caption:"JSON Example"
});
jQuery("#list2").jqGrid('navGrid','#pager2',{edit:false,add:false,del:false});
});
</script>
Have tried a number of things to get it to work. Nothing seems to do it.
I find the question very interesting. So I modified a little your code and it work now. You can see the results live here.
The corresponding JavaScript code is following
jQuery(document).ready(function() {
jQuery("#list2").jqGrid({
url: 'http://tables.googlelabs.com/api/query?sql=' +
encodeURI('SELECT * FROM 333136 LIMIT 10') + '&jsonCallback=?',
postData: "", // don't send any typical jqGrid parameters
datatype: "json", // or "jsonp"
colModel:[
{name:'ident',index:'ident',key:true,width:60,sorttype:'int'},
{name:'date',index:'date', width:130},
{name:'sourceId',index:'sourceId',width:80,sorttype:'int'},
{name:'source',index:'source',width:150},
{name:'tags',label:'tags',width:350}
],
jsonReader: {
cell: "", // the same as cell: function (obj) { return obj; }
root: "table.rows",
page: function (obj) { return 1; },
total: function (obj) { return 1; },
records: function (obj) { return obj.table.rows.length; }
},
rowNum:10,
rowList:[10,20,30],
pager: '#pager2',
sortname: 'id',
sortorder: "desc",
viewrecords: true,
loadonce: true,
height: "100%",
caption: "How to query Google Fusion Tables"
});
jQuery("#list2").jqGrid('navGrid','#pager2',{edit:false,add:false,del:false});
});