I've been trying to get DataTables to work with my existing Ajax search function - which works by itself.
I have the following code:
$('#SearchResults').dataTable({
"bProcessing": true,
"bServerSide": true,
"bRetrieve": true,
"sAjaxSource": "process.php?action=searchArtifact",
"fnServerData": function (sSource, aoData, fnCallback){
aoData.push({
"name": "searchName",
"value": $('#ArtifactSearch').attr('value')
});
$.ajax({
"dataType": "json",
"type": "POST",
"url": sSource,
"data": aoData,
"success": fnCallback
});
}
});
The PHP is returning a valid JSON object (using JSON_FORCE_OBJECT):
{"0":{"ARTIFACT_ID":"4E2FE3BCE356C","ARTIFACT_NAME":"123","ARTIFACT_TYPE":"UI","ARTIFACT_LABEL":"Test_Int_EAS_123","ARTIFACT_LOCATION":"Int","ARTIFACT_DOMAIN":"ABC","ARTIFACT_AUTHOR":null,"REGISTERED_EMAIL":"test#test.com","REGISTERED_DATE":"27-07-2011","REGISTERED_TIME":"11:09:00"}
I can see this all fine in FireBug, but my empty table is not being populated with this data.
Any ideas?
#Kyle: Errr - thats it. I guess I don't have one? This is my first attempt (struggle) with DataTables and I'm just copying from the documentation: http://www.datatables.net/usage/callbacks#fnServerData
#MarcB: Added that - but still no data displayed. Thanks for the help
I was having a similar problem. Turns out I wasn't forming the JSON response properly. This worked for me:
<?php
$arr = array ('aaData' => array(
array('3','35','4', '$14,500', '$15,200','$16,900','5','1'),
array('1','16','4', '$14,200', '$15,100','$14,900','Running','1'),
array('5','25','4', '$14,500', '$15,600','$16,900','Not Running','1')
)
);
echo json_encode($arr);
?>
This plugin expects the returned JSON object to be an object, with a property which is an array of arrays. This property should be called 'aaData'. You are not returning an object; you are just returning the array.
Check out this json resource example from DataTables.net: http://datatables.net/examples/examples_support/json_source.txt. Notice that you are returning json with brackets as compared to the example's braces.
you can remove the $.ajax part, instead you can use the $.getJSON method.
You can also add the following to avoid adding an extra object like "aaData":
"sAjaxDataProp": ''
What are you setting sEcho to?
Your JSON should have this structure:
{
"sEcho": 'refer to "sEcho" in $_GET or $_POST; don't forget to sanitize',
"iTotalRecords": 'for pagination',
"iTotalDisplayRecords": 'number displayed',
"aaData" => { /* your data here */ }
}
This is a few years late but might help someone. :)
DataTable cannot render null values. See defaultContent to set content when data return is null.
See link: https://datatables.net/reference/option/columns.defaultContent
For legacy dataTables, see http://legacy.datatables.net/ref and search for sDefaultContent
Related
I am unable to append the values to data tables, PHP file giving the JSON response but I am unable to append the data to the data table. I have used the following code for JSON response
GetKeyWordBids.php
array_push($ret, array("keyword"=>$keyword, "svol"=>$search_volume));
}
//print_r($ret);
echo json_encode($ret);
And Json Response:
[{
"keyword": "interventional cardiology",
"svol": 6600
},{
"keyword": "pediatric cardiology",
"svol": 5400
},{
"keyword": "cardiology jobs",
"svol": 1300
},{
"keyword": "cardiology associates",
"svol": 6600
},{
"keyword": "interventional cardiology jobs",
"svol": 880
},{
"keyword": "european society of cardiology",
"svol": 5400
},{
"keyword": "nuclear cardiology",
"svol": 1600
}],
And My Jquery Code is :
$('#specialty').change(function(){
$("#example1").dataTable().fnDestroy();
var oTable = $('#example1').dataTable({
"aaSorting": []
});
var spevalue = $("#specialty option:selected").text();
var dataString='specialty='+ spevalue;
$.ajax({
type: "POST",
url: "GetKeyWordBids.php",
data: dataString,
success: function(s){
oTable.fnClearTable();
for(var i = 0; i < s.length; i++) {
oTable.fnAddData([
s[i]['keyword'][0],
s[i]['svol'][0]
]);
}
});
});
But I am getting the error shown below. Please let me know the changes that are required.
DataTables warning (table id = 'example1'): Requested unknown parameter '0' from the data source for row 0
The JSON parser is very strict about JSON. And then your actual recall of the data is badly formatted. So:
As per splash58's comment, make sure your dataType is JSON. In your browser's developer tools (or Firebug), look at the XHR. The tool should provide a tab for viewing the response as formatted JSON. If it doesn't, or if you saw an error on the request, it might be requested with bad headers, or returned with the wrong type.
The trailing comma might be ignored by a JavaScript interpreter in general, but the JSON parser is strict and won't like it. A quick way of double-checking your JSON formatting is to fire it into JSONLint.com to see if it validates. The one you supply above does not until you remove the comma at the end.
I assume you want the full "keyword" and "svol". The extra [0] is digging into the string and returning the first character. You're going too deep into the data! What you want is s[i]['keyword'] (or s[i].keyword) and s[i]['svol'] (or s[i].svol) per this fiddle: http://jsfiddle.net/v07tvuq8/
I'm not really sure that the combination of fnClearTable and fnAddData are what you are looking for. The DataTables API allows you to specify what each column should do at initialization time, and thereafter you should just need to call draw() on it. There shouldn't be a need for iterating over your data set.
I have following array tree in json which is passed to view in a variable
[{
"root":"0",
"id":"19",
"name":"Rose",
"childs":[{
"root":"19"
"id":"22",
"name":"Ceema",
"childs":[{
"root":"22",
"id":"49",
"name":"Chandar"
},
{
"root":"22",
"id":"50",
"name":"Carol"
}]
},
{
"root":"19",
"id":"23",
"name":"Ben"
}]
}]
now i want that at first it displays the name of array with root 0, when we click on that name, it shows the name contained in arrays within child(if it has any).
M not so good with json, so please help!
Use json_decode() function in php or if you want to do it in javascript JSON.parse
This will give you result in array and rest things you need to do or find the code for it.
I'm trying to make a simple ajax call in datatables that is reliant on a post array of IDs from a previous page's form. I am getting the error :
Invalid JSON Response
which tells me that my returned json array is probably empty or something and I have a feeling it has to do with the POST data not being sent to my php/sql external script on which ajax is requesting the data from.
I'm not sure how to test it as I don't know how to include the $_POST data in the URL to my external php page to outright trigger the script.
Heres my current datatables init and php from the results page:
<?php
include_once('../functions.php');
sec_session_start();
print_r($_POST['post_id']); <-- making sure the post data made it this far
?>
<script type="text/javascript">
$(document).ready(function() {
var compTable = $('#compTab').dataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "baddebt_ext_sql.php",
"type": "POST",
"dataType": 'json',
"data": {"post_id": $_POST['post_id']}
},
"Columns": [
{ "data": "provider_num" },
{ "data": "provider_name"},
{ "data": "261_total_bed_debts", "sClass": "rightAlign" },
{ "data": "271_medicare_bad_debts", "sClass": "rightAlign" },
{ "data": "281_non_medicare_bad_debts", "sClass": "rightAlign" },
{ "data": "1_cost_to_charge_ratio", "sClass": "rightAlign" },
{ "data": "291_cost_of_non_mcr_bad_debts", "sClass": "rightAlign" }
],
"scrollY": "600px",
"scrollCollapse": true,
"paging": false,
"order": [[ 2, "desc" ]],
"oLanguage": { "sSearch": "Filter All Fields By:" },
"Dom": '<"clear">lfrtipT',
"TableTools": {
"sSwfPath" : "../php/tabletools/swf/copy_csv_xls_pdf.swf" }
});
and here is my SQL:
<?php
include_once('../link_costreport_2013.php');
if(isset($_POST['post_id'])){
$in = $_POST['post_id']; <-- THIS IS WHERE THE POST DATA IS SUPPOSED TO BE RECEIVED
}
$data = array();
foreach ($in as $id){
$query = $link->prepare("SELECT id,provider_num, provider_name, 261_total_bed_debts, 271_medicare_bad_debts, 281_non_medicare_bad_debts, 1_cost_to_charge_ratio, 291_cost_of_non_mcr_bad_debts
FROM `s10`
WHERE `id` = :id");
$query->bindParam(':id', $id, PDO::PARAM_INT);
$query->execute();
$results = $query->fetch(PDO::FETCH_ASSOC);
$results['261_total_bed_debts'] = "\$".number_format($results['261_total_bed_debts']);
$results['271_medicare_bad_debts'] = "\$".number_format($results['271_medicare_bad_debts']);
$results['281_non_medicare_bad_debts'] = "\$".number_format($results['281_non_medicare_bad_debts']);
$results['291_cost_of_non_mcr_bad_debts'] = "\$".number_format($results['291_cost_of_non_mcr_bad_debts']);
$results['provider_name'] = "<a id='".$results['id']."' data-toggle='modal' href='#provmodal' class='push'>".$results['provider_name']."</a>";
$data[] = $results;
}
echo json_encode($data);
If anyone knows how I can get my json array from this script without utilizing the previous pages $_POST data it is supposed to send, then I will gladly post it as well.
Basically I'm just wondering if there are any steps I am missing when it comes to feeding this array of IDs through my datatables ajax query and into the second page's sql. ( an example of the post_id array is like this:
Array ( [0] => 299 [1] => 1555 [2] => 3539 ))
Diagnosing this problem is pretty easy. Simply right mouse click and "inspect element" then choose the Network tab. Toggle the transaction as you would in your interface. You'll see a new network transaction in the network tab.
Click on that new network transaction -- it should have the address that you're defining in the ajax call. The headers will show the variables you sent via post, response will show what the server returned.
The error is indicating that your response will fail if you paste the payload into jslint.com and evaluate it. What the cause of that failure is will require more details than you've provided.
In the ajax example you use, "data" is the data that's being sent to the server. To send a large amount of data in that post, I'd enclose your inputs in a form tag, then do a $.serialize or $.serializeArray on that form. You can then send that serialized data over as a variable via the data attribute, where it will be posted to your server. From there, just deal with the resulting post variables via PHP.
Please do update your code to use 1.10 API variables. Support for the old ones will be deprecated in the future versions.
I am currently having an issue learning the basics of Ember and how it communicates with a backend service.
Here is what I'm doing in router.js:
Rugby.RugbyRosterRoute = Ember.Route.extend({
model: function(){
return [{
firstname:$.getJSON("/RugbyAPI")
// $.getJSON("/RugbyAPI") returns "John"
}];
//return this.store.find('roster');
},
renderTemplate: function(controller) {
this.render('rugby/roster', {controller: controller});
// tried this as well
//this.render('rugby/roster', controller);
}
});
But this is whats rendered.... [object Object]
I guess my question is how would I deal with this 'object'. I have been stuck for the past day but now luck...
EDIT:
I run this command in the web browser console...
$.getJSON("/RugbyAPI", function(data) { console.log(data) });
This is the result:
-> Object {readyState: 1, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}
-> John
My guess is that I have to parse to the key that I need to display... But I can't seem to parse to it.... ['responseJSON'], ['firstname'], etc., nothings working...
{controller: controller}
Is an object.
Try:
this.render('rugby/roster', controller);
or:
this.render('rugby/roster', controller.propertyName);
I chose to use JIT.js rgraph for a project I am working on. What I've done was taken the examples and began slowly merging the js into the projects core files. Simple! The hang up I've run into has me literally stumped.
example.js has (assumed to be hand written at some point) json like so.
var json = {
id: "190_0",
name: "Pearl Jam",
children: [{
id: "306208_1",
name: "Pearl Jam & Cypress Hill",
data: {
relation: "<h4>Pearl Jam & Cypress Hill</h4><b>Connections:</b><ul><li>Pearl Jam <div>(relation: collaboration)</div></li><li>Cypress Hill <div>(relation: collaboration)</div></li></ul>"
},
children: [{
id: "84_2",
name: "Cypress Hill",
data: {
relation: "<h4>Cypress Hill</h4><b>Connections:</b><ul><li>Pearl Jam & Cypress Hill <div>(relation: collaboration)</div></li></ul>"
},
children: []
}]
},...
I need the json file dynamically generated in a sense and the most productive way for me to use the json is to create a static file if/when relative parts of the project are updated instead of generating json every time the page loads. Makes sense right?
json.php looks like this
$project = array(
"id" => "1",
"name" => "Testing Project",
"children" => array (
"id" => "2",
"name" => "Sub 1",
"data" => array(
"relation" => "<h4>Testing Project</h4><b>Structure:</b><ul><li>Sub1</li><li>Section 1</li></ul>"
),
"children" => array(
"id" => "3",
"name" => "Section 1",
"data" => array(
"relation" => "<h4>Section 1</h4><b>Structure:</b><ul><li>Testing Project</li><li>Sub 1</li></ul>"
),
"children" => ''
)
)
);
// header('Content-type: application/json'); /* DOES NOTHING */
echo json_encode($project);
my Arrays are hand written at the moment to make sure the process works as intended before programmatically generating the arrays from the database. There are other pieces to the puzzle I do not believe are at all involved at this time but the next piece we need to look at is the ajax call to fetch json.php which is in my custom.js file.
function init() {
var json = (function () {
var json = null;
$.ajax({
'async': false,
'global': true,
'url': 'js/json.php',
'dataType': "json",
'success': function (data) {
json = data;
console.log(data);
}
});
return json;
})(); ... continue with JIT.js functions
I added console.log(data) to see if the json was coming back formatted and this is what that looks like console.log screenshot using custom.js ajax call So then I reused the example.js file and console.log(data) give us console.log screenshot using example.js
The only obvisou difference is that the example.js json is be represented as an array, not an object. Even stranger still is that when I run the example using the custom.js file with the ajax call "Testing Project" does appear on the graph but no children elements. In the screenshot for custom.js console.log shows all the children elements as children: object, not children:Array[] like example.js
My first thought was to see if I can ensure that all json_encoding forced the associative arrays into "arrays". And yea... lots of time wasted looking at the obvious. So my next thought was it must be in the formatting. example.js used [{ for each child element but json_encode does not. I cannot locate any information to confirm if that really is the problem or not, but, none the less I cant rule that out. I also checked into sequential indexes. example.js certainly does not have sequential indexes. I even went ahead and sorted the arrays before encoding json_encode(array_values($project)); to see what happens and while it outputs to a browser with indexes it of course shows nothing in the graph.
I feel like im spinning in circles ( not in the good eagle circling prey kinda way ) but getting to far off focus to figure this out. I need some fresh perspective and ideas what might be going wrong.
**Edit
I've also tried to convert the strings manually with PHP. still not working. Any ideas?
WOW, Just over 24 hours and I end up doing something like this. It works by making each child with content an array of arrays.
$test = array(
'id' => "1",
'name' => "testing sample",
'children' => array(
array(
...
),array(
...
'children' =>array(),
),
)
);
echo json_encode($test);