jqGrid call restful service successfully but failed to show the jqGrid ui - json

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).

Related

How can I read a CSV file with headers in Webix datatable?

I want to read a CSV file with headers to populate a datatable widget following this documentation. However, I get an uncaught exception: [object XMLHttpRequest] error when I execute the following code:
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" href="http://cdn.webix.com/edge/webix.css" type="text/css">
<script src="http://cdn.webix.com/edge/webix_debug.js" type="text/javascript"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="//cdn.opencpu.org/opencpu-0.4.js"></script>
</head>
<body>
<script type="text/javascript" charset="utf-8">
webix.ui({
rows:[
{ view:"template",
type:"header", template:"Read in a CSV" },
{ view:"datatable",
columns:[
{ id:"#x#", header:"x" },
{ id:"#y#", header:"y" },
{ id:"#z#", header:"z" }],
datatype:"csv",
autoheight:true,
autowidth:true,
url:"data/basic.csv"
}
]
});
</script>
</body>
</html>
In addition, I see the following notifications appear in the upper right-hand corner of the browser.
The error details from the log are:
"XHTTP:" XMLHttpRequest { onreadystatechange: webix.ajax.prototype._send/x.onreadystatechange(), readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, status: 0, statusText: "", responseType: "", response: "x,y,z
1,1,23.3
1,2,15.8
2,1,88.3
2,2,83.5
", responseText: "x,y,z
1,1,23.3
1,2,15.8
2,1,88.3
2,2,83.5
" } webix_debug.js:3240
uncaught exception: [object XMLHttpRequest]
It appears to read the CSV file just fine. Why doesn't it display? I have to admit, I find the documentation confusing as it doesn't mention CSV headers at all.
Are you run the sample page by the http (with some kind of web server), or open it directly from a file system?
Due to security limitations, ajax request may not work for pages that was loaded directly from a file system.
Also, to map data correctly, you need to use datatable columns config like next
columns:[
{ id:"data0", header:"x" },
{ id:"data1", header:"y" },
{ id:"data2", header:"z" }],
DataTable will not recognize header and map CSV data to abstract data0..dataN properties.

Empty error message with jQuery.jTable

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();
}
});
});
},
},

d3.js import csv using accessor function and callback

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.

JQuery/Zepro $.ajax request always fails in Firefox/Chrome works in Safari

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

How to extract data from Tumblr API (JSON)?

I have set up a Tumblr account and registered my application to authenticate it.
Tumblr Documentation: http://www.tumblr.com/docs/en/api/v2
I understand the API outputs JSON like this:
{
"meta": {
"status": 200,
"msg": "OK"
},
"response": {
"blog": {
"title": "David's Log",
"posts": 3456,
"name": "david",
"url": "http:\/\/david.tumblr.com\/",
"updated": 1308953007,
"description": "<p><strong>Mr. Karp<\/strong> is tall and skinny, with
unflinching blue eyes a mop of brown hair.\r\n
"ask": true,
"ask_anon": false,
"likes": 12345
}
}
}
Thats fine, but the documentation ends there. I have no idea how to get this information and display it on my site.
I thought the way you would get it would be something like:
$.ajax({
url: "http://api.tumblr.com/v2/blog/myblog.tumblr.com/info?api-key=myapikey",
dataType: 'jsonp',
success: function(results){
console.log(results);
}
});
But this does nothing.
Can anyone help me out? Thanks
results is now the object you can use to reference the JSON structure. When you console.log the results object, it should appear in the Javascript developer console where you can explore the object tree.
The response object
So when your success callback receives the response, the following should be available to you:
results.meta.status => 200
results.meta.msg => "OK"
results.response.title => "David's Log"
results.response.posts => 3456
results.response.name => "david"
results.response.url => "http://david.tumblr.com/"
results.response.updated => 1308953007
results.response.description => "<p><strong>Mr. Karp</strong>.."
results.response.ask => true
results.response.ask_anon => false
results.response.likes => 12345
Writing to the page
If you actually want to see something written to your page you'll need to use a function that modifies the DOM such as document.write, or, since you're using Jquery, $("#myDivId").html(results.response.title);
Try this:
Add <div id="myDivId"></div> somewhere in the of your page, and
Add $("#myDivId").html(results.response.title); in your success callback function
$.ajax({
url: "http://api.tumblr.com/v2/blog/myblog.tumblr.com/info?api_key=myapikey",
dataType: 'jsonp',
success: function(results){
// Logs to your javascript console.
console.log(results);
// writes the title to a div with the Id "myDivId" (ie. <div id="myDivId"></div>)
$("#myDivId").html(results.response.title);
}
});
In the question code, the request type was not being set and it was being rejected by tumblr. The jsonp error response was printing-out. The code below correctly makes the jsonp request.
The key was specifying the type, and the dataType. Good Luck happy hacking. ;-)
$.ajax({
type:'GET',
url: "http://api.tumblr.com/v2/blog/jdavidnet.tumblr.com/info",
dataType:'jsonp',
data: {
api_key : "myapikey"
},
success:function(response){
console.log(response, arguments);
}
});
One way to write an object to the screen is to add an element containing its JSON representation to the page:
$.ajax({
url: "http://api.tumblr.com/v2/blog/myblog.tumblr.com/info?api-key=myapikey",
dataType: 'jsonp',
success: function(results){
$("body").append(
$("<pre/>").text(JSON.stringify(results, null, " "))
);
}
});
Here is a demonstration: http://jsfiddle.net/MZR2Z/1/