Datatable - JSON not being shown of size larger than 4KB - php

I am using data table to display data returned by a SQL Server 2008 procedure called in Codeigniter via Ajax($POST). Initially I made a very simple procedure with no input parameters, it only returns a list of JSON objects.
Below are my questions and my Codeigniter function returning JSON, AJAX function and JSON structure returned by my Codeigniter function:
1) JSON not returned for chunk larger than 4KB, it simply converts to HTML:
2) What if one of my procedure returns lets say 5000+ record and i want to display it in data table, is my way of doing it right? Or i should use some other best practices:
Codeigniter Function:
public function executeProc()
{
$sqlsrvr = $this->load->database('test', true);
// Get the input values of the procedure
$arr = array();
parse_str($_POST['str'],$arr);
//get Procedure Name
$procName = $_POST['procName'];
$sp ='exec secondProc';
$query = $sqlsrvr->query($sp);//->result();
$jawad = $query->result_array();
$this->output->set_header('Content-type: application/json');
echo json_encode($jawad);
}
AJAX Function
$(document).on('click','#executeProc',function(e){
$('#demo').html('<table cellpadding="0" cellspacing="0" border="0" class="display" id="example"></table>');
e.preventDefault();
var jawad = $( ".jawad" ).serialize();
$.post('<?=base_url();?>command/executeProc',
{str:jawad,procName:$('#procName').val()},
function(html){
//loading data table on return
$('#example').dataTable( {
"data": html,
"columns": [
{ "data": "AppointmentID" },
{ "data": "FirstName" },
{ "data": "LastName" },
{ "data": "AppointmentDate" }
]
} );
});
});
JSON Sample:
[
{
"AppointmentID": "1",
"FirstName": "Test",
"LastName": "test",
"AppointmentDate": "2013-01-12"
},
{
"AppointmentID": "2",
"FirstName": "dfg",
"LastName": "dfg",
"AppointmentDate": "2013-01-01"
}
]
-----AFTER EDIT------
STRANGE BEHAVIOR(JSON tab converts to HTML for larger records)
FOR 40 records that get displayed on data table
FOR records larger then 40 that don't get displayed on data table

Related

Assign Json file objects to variables

I have a JSON file that I would like to use with PHP to assign variables to the individual objects.
The file looks like this: (Is this a valid JSON file?):
{"draw":0,
"data":[
["123456789",
"first_data_one",
"second_data_one",
"third_data_one",
"fourth_data_one",
"fith_data_one"],
["7656576657",
"first_data_two",
"second_data_two",
"third_data_two",
"fourth_data_two",
"fith_data_two"],
],
"recordsTotal":"181",
"recordsFiltered":"181"
}
I need some help assigning each values,
EX: number = "123456789", $first_data = "first_data_one", $second_data = "second_data_one", $third_data = "third_data_one", $fourth_data = "fourth_data_one", $fith_data = "fith_data_one" to variables.
In the end I want to echo each, some thing like this:
echo Number: $number;
echo Number: $first_data;
echo Number: $second_data;
echo Number: $third_data;
echo Number: $fourth_data;
echo Number: $fith_data;
I want to put it all in a table in the end.
Your table header contains names for columns
<thead>
<tr>
<th>Number</th>
<th>first_data</th>
<th>second_data</th>
<th>third_data.</th>
<th>fourth_data</th>
<th>fith_data</th>
</tr>
</thead>
one way is to define columns, but then your return object based , columns as key
$('#myjson').dataTable( {
"ajax": { "url": "api/data.json",
"dataSrc": "data" } , // default datasrc is data, so no need of it
"columns": [
{ "data": "number" },
{ "data": "first_data" },
{ "data": "second_data" },
{ "data": "third_data" },
{ "data": "fourth_data" },
{ "data": "fith_data" }
]
} );
this will automatically assign data to columns
the header will be your html header,
like you have 6 columns and your json also has 6 so it will be fine
$('#myjson').dataTable( {
"ajax": { "url": "api/data.json"}
} );
and if you switch on serverside processing
then you get these
"recordsTotal": 57, "recordsFiltered": 57,
have a look at the api docs

CodeIgniter: Select the same like parameter on JSON list

I'm trying to use tokeninput from jQuery Token input, but the data is from the API. I already got the data from API and made a JSON list (see below).
When a user inputs in my token input, it will select from the JSON list, like user/auto_unit?queryParam=q for example. It already gets the user input correctly, but it still returns all data, even those that do not match the user input.
What I want is when the user searches for "Sosiologi", the only values that would show are those string which have "sosiologi" in them.
Is it possible to get only the same values and how can I do that? Thanks in advance!
My JSON list:
// 20170401095401
// http://exp.uin-suka.ac.id/aspirasi/user/auto_unit?queryParam=Filsafat%20Agama
[
{
"id": "UA000001",
"name": "Filsafat Agama"
},
{
"id": "UA000002",
"name": "Perbandingan Agama"
},
{
"id": "UA000003",
"name": "Ilmu Al-Qur'an dan Tafsir"
},
{
"id": "UA000004",
"name": "Sosiologi Agama"
},
{
"id": "UA000005",
"name": "Matematika"
},
{
My JSON code to get the list
function auto_unit() {
$data['unit'] = $this->m_simpeg->getAllUnit();
foreach ($data['unit'] as $key ){
$row['id']= $key['UNIT_ID'];
$row['name']= $key['UNIT_NAMA'];
$row_set[] = $row;
}
echo json_encode($row_set);
}
Model to get API M_simpeg.php:
public function getAllUnit(){
return $this->s00_lib_api->post_api(
1001, 1, null,
URL_API_SIMPEG.'simpeg_mix/data_view'
);
}
Check your server side code as it is not filtering the array.
Codeigniter sample code
<?php
function filter(){
$queryParam=$this->input->get('queryParam');
$res=$array.filter($queryParam);
return $res;
}
?>

retrieve json encoded multidimensional array with ajax

I successfully (tested) call an ajax request to a php script. This is the portion of code i need to make working:
success: function (response, status) {
$.each(response, function (i, item) {
alert(item.id);
item.id is just...nothing.
This is the generated - json_encoded array by php page:
[
{
"conto": "1"
},
{
"id": "4",
"activity_id": "50",
"path": "Testo/base.png",
"title": "Ffgf",
"descrizione": "Tttt"
},
{
"id": "8",
"activity_id": "50",
"path": "Testo/61FCFUX_IMG_0536.PNG",
"title": "Hggggg",
"descrizione": "Tgg"
}
]
What do I do wrong?
p.s: if you noticed, this is an array merge between two arrays: the first one just reports "conto" in in, the other one is a list generated by fetching elements by database.
Your first array not containing id so you are getting undefined value. Skip first array:
$.each(response, function (i, item) {
if(i==0)
{
alert(item.costo);
}
else
{
alert(item.id);
//Or better to use console
console.log(item.id);
}
});
I believe your issue is with your reference. Since your JSON object contains an array you will need to reference it with subscripts. Try changing item.id to item[i].id. That way as the each function iterates through the array, it can reference the id field in each object.
Edit: Here's working code.
$(document).ready(function (){
var source = '[{"conto":"1"},{"id":"4","activity_id":"50","path":"Testo\/base.png","title":"Ffgf","descrizione":"Tttt"},{"id":"8","activity_id":"50","path":"Testo\/61FCFUX_IMG_0536.PNG","title":"Hggggg","descrizione":"Tgg"}]';
source = JSON.parse(source);
var cellcount = length(source);
for(var i = 0; i < cellcount; i++){
console.log(source[i].id);
}
});
function length(obj) {
return Object.keys(obj).length;
}

DataTables - Dynamic Columns From Ajax Data Source?

I am trying to get DataTables to read the column names from an AJAX data source but it seems that there must be something that I must be missing here.
I made a fiddle fiddle in which I can manually define the data and columns that are being used by the table.
The table is declared in the HTML and there is no no need to define the column names (<thead>..</thead>):
<table id="example" class="display table table-striped table-bordered"
cellspacing="0" width="100%"></table>
In the JS we manually define the data:
var data = [
[ "Row 1 - Field 1", "Row 1 - Field 2", "Row 1 - Field 3" ],
[ "Row 2 - Field 1", "Row 2 - Field 2", "Row 2 - Field 3" ],
];
Then manually define the column names or titles:
var columns = [
{ "title":"One" },
{ "title":"Two" },
{ "title":"Three" }
];
Then when we initialise the table we simply pass the previously declared information across for DataTables to use:
$(document).ready(function() {
$('#example').DataTable( {
dom: "Bfrtip",
data: data,
columns: columns
});
});
Which results in:
Now my question is how would I get this to work if the data is included in the AJAX server side response?
I have tried this in various ways and forms but nothing really seems to work out here and I am battling to find relative documentation on this.
For example if the server side processing sent back a JSON response which includes the column names at the end:
{
"data": [
{
"id": "1",
"One": "Row 1 - Field 1",
"Two": "Row 1 - Field 2",
"Three": "Row 1 - Field 3"
},
{
"id": "2",
"One": "Row 2 - Field 1",
"Two": "Row 2 - Field 2",
"Three": "Row 2 - Field 3"
}
],
"options": [],
"files": [],
"columns": [
{
"title": "One",
"data": "One"
},
{
"title": "Two",
"data": "Two"
},
{
"title": "Three",
"data": "Three"
}
]
}
Given this is the response, I tried to configure DataTables to use an AJAX data source for the row information as follows:
$(document).ready(function() {
$('#example').DataTable( {
dom: "Bfrtip",
"ajax": '/test.php',
columns: columns
});
});
But obviously columns is undefined here.
So I get the column data before hand:
function getPromise() {
var deferred = $.Deferred();
var dataUrl = document.location.origin+'/text.php';
$.getJSON(dataUrl, function(jsondata) {
setTimeout(function() {
deferred.resolve(jsondata);
}, 0);
}).fail(function( jqxhr, textStatus, error ) {
// ********* FAILED
var err = textStatus + ", " + error;
console.log( "Request Failed: " + err );
});
return deferred.promise();
}
// Get the columns
getPromise().done(function(jsondata) {
columns = jsondata.columns;
console.log(columns);
});
And pass it to DataTables as above. But this time all I get when running the example is an error in the console saying TypeError: p is undefined.
So then how could I make use of the dynamically generated columns that are being returned within the server side response? Is there not a simpler way to achieve this?
EDIT:
DataTables Editor code for server side processing / to generate the JSON response mentioned above:
<?php
// DataTables PHP library
require_once '/path/to/DataTables.php';
// Alias Editor classes so they are easy to use
use
DataTables\Editor,
DataTables\Editor\Field,
DataTables\Editor\Format,
DataTables\Editor\Mjoin,
DataTables\Editor\Upload,
DataTables\Editor\Validate;
// Build our Editor instance and process the data coming from _POST
$out = Editor::inst( $db, 'example' )
->fields(
Field::inst( 'id' )->set(false),
Field::inst( '`One`' )->validator( 'Validate::notEmpty' ),
Field::inst( '`Two`' )->validator( 'Validate::notEmpty' ),
Field::inst( '`Three`' )->validator( 'Validate::notEmpty' )
)
->process( $_POST )
->data();
// On 'read' remove the DT_RowId property so we can see fully how the `idSrc`
// option works on the client-side.
if ( Editor::action( $_POST ) === Editor::ACTION_READ ) {
for ( $i=0, $ien=count($out['data']) ; $i<$ien ; $i++ ) {
unset( $out['data'][$i]['DT_RowId'] );
}
}
// Create the thead data
if (count ($out) > 0) {
$columns = array();
foreach ($out['data'][0] as $column=>$relativeValue) {
// Add all but the id value
if ($column !== 'id') {
// Add this column name
$columns[] = array(
"title"=>$column,
"data"=>$column
);
}
}
}
// Add the the thead data to the ajax response
$out['columns'] = $columns;
// Send the data back to the client
echo json_encode( $out );
If you don't use the built in DataTables ajax it should be easy enough given the structure of your data:
$(document).ready(function() {
$.ajax({
type: 'POST',
dataType: 'json',
url: '/echo/json/',
data: {
json: JSON.stringify(jsonData)
},
success: function(d) {
$('#example').DataTable({
dom: "Bfrtip",
data: d.data,
columns: d.columns
});
}
});
});
Like this JSFiddle, you're limited then to loading all the data at once but that shouldn't be a huge issue... unless you alter it get the columns from the initial ajax call and once the DataTable is initiated then add the built-in ajax - I've not tried this though...
You must create the table in html without header
<table id="tablaListadoExpediciones" class="table table-bordered table-striped dt-responsive"> </table>
Now you have to generate the columns array dynamically. In this way, the columns will always be generated automatically even if the AJAX response varies over time.
function PintarTablaDinamicamente(datos) {//object "datos" comes from AJAX response
//I take the keys of the object as columns of the table
var arrColumnas = Object.keys(datos[0])
////In case you wanted to hide a column
//var indiceColumna = arrColumnas.indexOf("nameOfTheColumnToHide")
//if (indiceColumna !== -1) {
// arrColumnas.splice(indiceColumna, 1)
//}
var columns = []
//columns must be in JSON format-->{data:'keyToSearchInJSON',title:'columnTitle'}
for (var i in arrColumnas) {
//if (arrColumnas[i] == "SELECCIONAR") { //if you want to add a checkbox in one colunm (for example column named SELECT
// columns.push({
// data: null,
// defaultContent: '',
// className: 'select-checkbox',
// orderable: false
// });
//} else {
columns.push({ data: arrColumnas[i], title: arrColumnas[i] });
//}
}
tabla = $('#tablaListadoExpediciones').DataTable({
dom: "Blfrtip",
data: datos,
//order: [[0, 'desc']],
"pageLength": 25,
"scrollX": true,
columns: columns
,
buttons: [
{
extend: 'copy'
},
{
extend: 'excel'
},
{
extend: 'print'
}
],
//select: {
// style: 'os',
// selector: 'td:first-child'
//}
});
}

getJSON not working correctly with codeigniter

I am trying to implement AJAX call method into my website using codeigniter, the reason why i want to use AJAX so i can get live updates from the database
The click button works and displays all of the JSON data but the issue is when i try and display a specific array it does not recognize it, it seems to be iterating through every single character.
Also another wierd thing is when the alert is being called i can see the html and head tags I want to be able to print specific arrays for example the array id"
Things i have done to try and work it out
i have alerted the datatype and found out it was a string
i have managed to get ajax to work in regular PHP rather then codeigniter so their is nothing wrong with the database
I have also tried to use jQuery.parseJSON so i can force it to be json but then the script did not run
I used JSONlint and apprently its a valid JSON
Any help would be appreciated
Consolelog
<html>
<head>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAXpGbk1wkkaPiv_qkBevxAP9s4kk0oiiU&sensor=false"></script>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
[
[
{
"id": "1",
"postcode": "NW6",
"imgurl": "hello.jpeg",
"from_user": "henny",
"created_at": "2013-03-18 23:03:00"
},
{
"id": "2",
"postcode": "NW2",
"imgurl": "test.jpeg",
"from_user": "belly",
"created_at": "2013-03-15 23:03:00"
}
]
]
Controller
public function insertJSON()
{
$this->load->model("values");
$queryresults = $this->values->getDb();
$arrays = array($queryresults);
echo json_encode($arrays);
}
View
<script type='text/javascript' language='javascript'>
$('#getdata').click(function (data) {
$.ajax({
url: '<?php echo base_url().'index.php/welcome/insertJSON';?>',
type: 'POST',
cache: 'false',
datatype: 'json'
}).done(function (data) {
alert(data);
});
});
</script>
json_encode
[
[
{
"id": "1",
"postcode": "NW6",
"imgurl": "hello.jpeg",
"from_user": "henny",
"created_at": "2013-03-18 23:03:00"
},
{
"id": "2",
"postcode": "NW2",
"imgurl": "test.jpeg",
"from_user": "belly",
"created_at": "2013-03-15 23:03:00"
}
]
]
You need to send the correct response headers back (application/json) from your controller function.
Try changing your controller to the following:
public function insertJSON()
{
$this->load->model("values");
$queryresults = $this->values->getDb();
$arrays = array($queryresults);
$this->output->set_content_type('application/json')
->set_output(json_encode($arrays));
}

Categories