I have a simple testing script:
<script type="text/javascript" language="javascript" >
$(document).ready(function() {
$('#dataTables-example').DataTable({
"processing": true,
"serverSide": true,
"ajax": "../server/studentsdata.php"
} );
} );
</script>
This is my json response:
{"draw":0,"recordsTotal":57,"recordsFiltered":57,"data":[["Tiger Nixon","320800","61"],["Garrett Winters","170750","63"],["Ashton Cox","86000","66"],["Cedric Kelly","433060","22"],["Airi Satou","162700","33"],["Brielle Williamson","372000","61"],["Herrod Chandler","137500","59"],["Rhona Davidson","327900","55"],["Colleen Hurst","205500","39"],["Sonya Frost","103600","23"],["Jena Gaines","90560","30"],["Quinn Flynn","342000","22"],["Charde Marshall","470600","36"],["Haley Kennedy","313500","43"],["Tatyana Fitzpatrick","385750","19"],["Michael Silva","198500","66"],["Paul Byrd","725000","64"],["Gloria Little","237500","59"],["Bradley Greer","132000","41"],["Dai Rios","217500","35"],["Jenette Caldwell","345000","30"],["Yuri Berry","675000","40"],["Caesar Vance","106450","21"],["Doris Wilder","85600","23"],["Angelica Ramos","1200000","47"],["Gavin Joyce","92575","42"],["Jennifer Chang","357650","28"],["Brenden Wagner","206850","28"],["Fiona Green","850000","48"],["Shou Itou","163000","20"],["Michelle House","95400","37"],["Suki Burks","114500","53"],["Prescott Bartlett","145000","27"],["Gavin Cortez","235500","22"],["Martena Mccray","324050","46"],["Unity Butler","85675","47"],["Howard Hatfield","164500","51"],["Hope Fuentes","109850","41"],["Vivian Harrell","452500","62"],["Timothy Mooney","136200","37"],["Jackson Bradshaw","645750","65"],["Olivia Liang","234500","64"],["Bruno Nash","163500","38"],["Sakura Yamamoto","139575","37"],["Thor Walton","98540","61"],["Finn Camacho","87500","47"],["Serge Baldwin","138575","64"],["Zenaida Frank","125250","63"],["Zorita Serrano","115000","56"],["Jennifer Acosta","75650","43"],["Cara Stevens","145600","46"],["Hermione Butler","356250","47"],["Lael Greer","103500","21"],["Jonas Alexander","86500","30"],["Shad Decker","183000","51"],["Michael Bruce","183000","29"],["Donna Snider","112000","27"]]}
But I keep receiving this error:
DataTables warning: table id=dataTables-example - Invalid JSON
response. For more information about this error, please see
http://datatables.net/tn/1
I tried to validate my json response on a few websites, and they all show it as valid. Why is Datatables rejecting it?
A update:
If I paste my json response directly on the php page, it works. Look like the json is right, but for some reason the script is not sending correctly. When I try to access the script directed (by accessing the .php page), I get the correct json.
Update!:
Maybe its because of extra properties you are passing into dataTable!
try to change php part to produce something like this :
{
"data":[
["name":"Tiger Nixon","value":"320800","age":"61"],
["name":"Garrett Winters","value":"170750","age":"63"]
.
.
.
]
}
This is the RESTful data format
{"user":[
{"id":"aupres","passwd":"aaa","age":45,"name":"father"},
{"id":"hwa5383","passwd":"bbb","age":40,"name":"mother"},
{"id":"julian","passwd":"ccc","age":15,"name":"son"}
]}
My jqGrid client call the above data successfully. The below image shows the result:
But this code fails to display the response to the jqGrid. This is my client code
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>jqGrid Test</title>
<link rel="stylesheet" type="text/css" media="screen" href="jquery-ui.css"/>
<link rel="stylesheet" type="text/css" media="screen" href="ui.jqgrid.css"/>
<script type="text/javascript" src="jquery-2.2.0.min.js"></script>
<script type="text/javascript" src="jquery.jqGrid.min.js"></script>
</head>
<body>
<table id="grid"></table>
<div id="pager"></div>
<script type="text/javascript">
$(document).ready(function(){
$Grid = $("#grid");
$Grid.jqGrid({
mtype: "get",
url: "/JQueryJsonWeb/rest/services/getJson/aupres",
contentType: "text/json; charset=utf-8",
dataType: "json",
jsonReader : {
root : "user"
},
colNames : [
'id',
'passwd',
'age',
'name'
],
colModel : [
{ name : 'id', width:40, align:'center'},
{ name : 'passwd', width:80, align:'left' },
{ name : 'age', width:80, align:'left' },
{ name : 'name', width:80, align:'right' }
],
pager : '#pager',
rowNum : '10',
loadComplete : onloadComplete,
loadError : onloadError,
gridComplete : ongridComplete
});
function onloadComplete(jsonData, status) {
console.log(jsonData) **// This method shows the above image.**
}
function onloadError(status) {
console.log(status)
}
function ongridComplete() {
console.log("fiished!!!");
}
});
</script>
</body>
</html>
Please read the comment to your previous question:
JavaScript is case sensitive language. There are NO dataType: "json" parameters and the default datatype: "xml" will be used.
Non-existing parameters contentType will be ignored too. The returned are wrong if one interpret there as XML data.
The output which you included come from onloadError and not from onloadComplete. The parameters of onloadError are jqXHR, textStatus, errorThrown. You included the console output of the jqXHR object. See the answer.
You should declare variables in JavaScript : use var $Grid = $("#grid"); instead of $Grid = $("#grid");. Including "use strict" directive at the beginning on top functions helps to detect such errors (see here). In the same way I'd recommend you include semicolon after every statement (see console.log(status) and console.log(jsonData)).
You should include in all your question which version of jqGrid you use and from which fork (free jqGrid - my fork, commercial Guriddo jqGrid JS or an old jqGrid in version <=4.7). The possibilities of the forks will be more and more different. Thus it's important which one you use (or can use).
I'm having problems with the jquery.jtable.js plugin.
My problem:
jTable continues to post this empty modal error message:
For your information:
I'm using NancyFX for my backend.
There are no 404s, everything is 200 OK
The objects I'm returning are plain POCOs, no proxies or anything of that nature
This is my HTML:
<!-- in the header -->
<script src="~/Scripts/jquery-1.9.1.js"></script>
<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
<link href="~/Scripts/jtable/themes/basic/jtable_basic.min.css" rel="stylesheet" />
<script src="~/Scripts/jtable/external/json2.min.js"></script>
<script src="~/Scripts/jquery-ui-1.9.2.min.js"></script>
<script src="~/Scripts/jtable/jquery.jtable.min.js"></script>
<!-- in body -->
<div id="UsersTableContainer"></div>
I have this javascript (whithin a $(document).ready()):
$('#UsersTableContainer').jtable({
title: 'All users',
paging: true,
pageSize: 10,
sorting: true,
defaultSorting: 'UserName ASC',
actions: {
listAction: '/api/backend/users/list',
},
fields: {
UserName: {
title: 'UserName',
key: true,
list: true,
width: '20%',
sorting: true
}/* and more
I've tried userName and UserName - nothing works
I've tried to map all properties and none, using a test column - nothing works */
}
});
$('#UsersTableContainer').jtable('load');
I can see with fiddler 2 that this is sent across the line:
{
"records": [
{
"userName": "user"
/*, more properties */
}/*, more records */
],
"result": "OK",
"message": "All OK", //tried with an without this, just to see if it pups up
"totalRecordCount": 2
}
Similar questions:
https://stackoverflow.com/questions/21360730/c-sharp-asp-net-jquery-jtable
Can't get data to load into jTable in mvc 4
I was having this same problem and found out, that in my case, I had changed the result from OK to SUCCESS and jTable was checking for OK. Upon further investigation I also found out that jTable is expecting the result property to be capitalized (i.e. Result). I didn't check, but I would guess that Records needs to be capitalized as does TotalRecordCount and Message. I hope this tidbit will help someone else.
I suggest you to solve in this way (this is listAction property of jTable plugin):
listAction: function (postData, jtParams) {
console.log("Loading from custom function...");
return $.Deferred(function ($dfd) {
$.ajax({
url: '/api/backend/users/list',
type: 'POST',
dataType: 'json',
data: {},
success: function (data) {
data.Records = data.records;
data.Result = data.result;
data.TotalRecordCount = data.totalRecordCount
delete data.result;
delete data.records;
delete data.totalRecordCount;
$dfd.resolve(data);
},
error: function () {
$dfd.reject();
}
});
});
},
},
I am trying to understand how to use d3.csv(url[, accessor][, callback]) using both the accessor and the callback function as specified in the official API documentation (see link for point 1). DISCLAIMER: I'm new to d3.js.
TL,WR: I get an empty console response to the console.log(data) command in the callback function and get undefined when I call console.log on the variable that should be holding the data.
I have found two easy examples to get to understand how it works.
The API itself has an example: d3.js API at github.com
A simple example at tonygarcia.me: Chart-data at tonygarcia.me
To execute these I have created both an html file for the code and a csv file with the data and then launched a simple server with the command python -m SimpleHTTPServer 8888 &.
Case 1: Official API documentation.
The html:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.js">
</script>
</head>
<body>
<script type="text/javascript">
var datas;
d3.csv("example.csv", function(d) {
return {
year: new Date(+d.Year, 0, 1), // convert "Year" column to Date
make: d.Make,
model: d.Model,
length: +d.Length // convert "Length" column to number
};
}, function(error, rows) {
console.log(rows);
datas = rows;
});
</script>
</body>
</html>
The csv (example.csv):
Year,Make,Model,Length
1997,Ford,E350,2.34
2000,Mercury,Cougar,2.38
The output on the console (empty) and then:
> console.log(datas);
undefined VM2228:2
undefined
The expected result:
[
{"Year": "1997", "Make": "Ford", "Model": "E350", "Length": 2.34},
{"Year": "2000", "Make": "Mercury", "Model": "Cougar", "Length": 2.38}
]
Case 2: Chart-data at tonygarcia.me
The html:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.js">
</script>
</head>
<body>
<script type="text/javascript">
var datas;
// load data from a CSV file
d3.csv('home.csv',
function(d) {
return {
key: d.state,
value: +d.value
};
}, function(dataset){
// code to generate chart goes here
datas = dataset;
console.log( dataset );
});
</script>
</body>
</html>
The cvs (home.cvs):
state,value
Alabama,71.6
Alaska,22.4
Arizona,147.5
Arkansas,59.9
<truncated>
The output on the console (empty) and then:
> console.log(datas);
undefined VM2265:2
undefined
The expected result (you can try it on the webpage):
[{"key":"Alabama","value":71.6},{"key":"Alaska","value":22.4},
{"key":"Arizona","value":147.5},{"key":"Arkansas","value":59.9},...]
So, what am I doing wrong? If I only use a callback function with no accessor everything works. Using the accessor is interesting to format the data from sting to f.e. number.
Thank you all for your help!
Best,
Michael
EDIT: Correction: tonygarcia.com --> tonygarcia.me
the callback should be set up like so:
d3.csv("your_file_url.csv", function (error, data) {
//Here you should put the code for your visualization.
});
Your first example would then be:
d3.csv("example.csv", function (error, data) {
console.log(data) // this will output the data contained in your csv
});
The fact is that the function d3.csv already parses the data as it gets loaded, so if you load the example.csv file it will be read and then treated like an array of values
It's a version issue. v3 works, v2 doesn't.
This code links to v2:
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.js">
</script>
To be exact it's contents are:
document.write("<script src='http://d3js.org/d3.v2.js'></script>");
To make it work I linked it to the newest version like this:
<script type="text/javascript" src="http://d3js.org/d3.v3.min.js">
</script>
This solves the main issue and I will consider the question solved. (Haven't figured out how Toni Garcia is doing it as I used his js and couldn't get it working, but this is irrelevant.)
Thanks all for your help and sorry for answering my own question.
I've just started trying to convert my first and still in development Webapp into a mobile app with Phonegap. I'm very confused with going from Server side page generation to client side page generation so I'm starting to do some basic stuff as test stubs, so I'll actually be able to get started writing my apps.
I'm trying to do an AJAX post with data to a Ruby Sinatra web service and receive a response in the browser. I can't get Firefox or Chrome to ever take the success path.
This is just testing right now, so it doesn't do anything useful or logical. The Sinatra route looks like this:
post "/auth/check" do
status 200
content_type :json
{ :login => true }.to_json
end
The html/javascript looks like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<!-- <script src="js/lib/zepto.min.js"></script> -->
<script src="http://code.jquery.com/jquery-2.0.3.min.js"</script>
<script src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js"</script>
<script>
var BASEURL = "http://localhost:4567";
function login(){
debugger;
$.ajax({
dataType: "jsonp",
url: BASEURL + '/auth/check',
type: "POST",
data: { email: 'somedude#example.com',
password: 'e'
},
success: function (result) {
alert(result);
},
error: function(xhr, type){
alert('Y U NO WORK?')
}
});
}
</script>
</head>
<body>
<input type="button" onClick="login()">Click Me</input"
</body>
</html>
I can't get Firefox or Chrome to do anything other than give the "Y U NO WORK?" alert. Any help would be much appreciated. I've tried switching from Zepto.js to JQuery/JQuery mobile, I've tried changing the data type to jsonp, using curl I've confirmed that the Sinatra route is returning something and a 200 status code which is what JQuery should be checking for.
The answer, based on help by Jan Dvorak, firstly I needed Sinatra to actually return JSONP data. Add a GEM for JSONP support:
require 'sinatra/jsonp'
Secondly the route can only be a HTTP GET, use the JSONP function to return something:
get "/auth/check/" do
content_type :json
status 200
#data = true
JSONP #data
end