DataTables Error: "Requested unknown parameter" - json
I'm new to the DataTables jquery plugin. After discovering that IE 8 had performance issues with Javascript I decided to change the way I use DataTables to do server side processing. I'm getting this error message when my JSP loads ( I'm using Spring 3 ):
DataTables warning (table id = 'results_table'): Requested unknown parameter '0' from the data source for row 0
I Googled around and found that many causes of that error message come down to malformed JSON so I found a way to output my JSON from my Spring 3 controller function to take a look at the JSON it makes and I changed my code to get it to be pretty close to what the DataTables site says it should look like.
Still no joy, still getting that error message.
The server side processing examples I found for DataTables didn't include code for specifying the columns used on the client side, so I assumed I don't need it. Do I?
Here are the relevant parts of my results.jsp:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>ACME: search results in a nice DataTables.net Plugin</title>
</head>
<body>
<link rel="stylesheet" type="text/css" href="css/jquery.dataTables.css" />
<script language = "JavaScript" type = "text/javascript" src = "../nsd/js/jquery-1.7.js"></script>
<script language = "JavaScript" type = "text/javascript" src = "../nsd/js/jquery.dataTables.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#results_table').dataTable( {
"bProcessing": true,
"bServerSide": true,
"sScrollX": "600px",
"sServerMethod": "POST",
"sAjaxSource": "/acme/resultstable",
} );
} );
</script>
<form id="command" name="f" action="employee" method="post">
<div id = "results">
<table id = "results_table">
<thead>
<tr>
<th> </th>
<th>ID</th>
<th>NO_PRINT</th>
<th>Full Name</th>
<th>Email Address</th>
<th>Phone Number</th>
<th>Organization</th>
<th>Organization Code</th>
<th>Position</th>
<th>Employee Type</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</body>
</html>
Here is the JSON response I've been sending to it:
{
"sEcho" : 1,
"iTotalRecords" : 1,
"iTotalDisplayRecords" : 1,
"aaData" : [ {
"person_id" : "888888",
"ID" : "999999",
"no_print" : " ",
"fullname" : "Obama, Willard",
"email_address" : "barry#whitehouse.gov",
"current_phone_number" : "303-867-5309",
"title" : " ",
"office" : " ",
"position" : "Contractor",
"empl_code" : "CONT"
} ]
}
Here is my Spring controller function I am using to send the JSON response via Jackson. This includes code to output my JSON so I can see what it looks like. Could the JSON it outputs to stdout and what I am sending back to DataTables be different?
#RequestMapping(value = "/resultstable", method = RequestMethod.POST)
public #ResponseBody LinkedHashMap resultstable(ModelMap model,
HttpSession session,
#RequestParam (required=true) int sEcho,
#RequestParam (required=true) int iDisplayStart,
#RequestParam (required=true) int iDisplayLength,
#RequestParam (required=true) int iColumns,
#RequestParam (required=true) int iSortCol_0,
#RequestParam (required=false)String sSortDir_0,
#RequestParam (required=true) String sSearch ) {
/*
**********************************************************************
** These come from the DataTables.net Jquery plugin on results.jsp
**********************************************************************
** sEcho, - just send it back, used by DataTables for synching
** iDisplayStart - index of the record to start with, ie 3 for the 3rd of 100 records
** iDisplayLength - number of records to send back starting with iDisplayStart
** iColumns - number of columns to be displayed in the table
** iSortCol_0 - the number of thee column to be sorted on
** sSortDir_0 - direction of sorting: asc or desc
** sSearch - from the search box, filter results further on this term
**********************************************************************
*/
String nextView = "results";
String usertype = (String)session.getAttribute("usertype");
Search search = new Search(usertype);
List<LinkedHashMap> records = null;
String results = null;
int number_of_records = (Integer)session.getAttribute("number_of_records_found");
ResultsView rv = new ResultsView();
ResultsScreenTableHolder rstrh = null;
SearchScreenDataHolder ssdh2 = (SearchScreenDataHolder)session.getAttribute("search_screen_data_holder");
ObjectMapper mapper = new ObjectMapper();
logger.debug("started");
logger.debug("sEcho, == " + sEcho );
logger.debug("iDisplayStart == " + iDisplayStart );
logger.debug("iDisplayLength == " + iDisplayLength );
logger.debug("iColumns == " + iColumns );
logger.debug("iSortCol_0 == " + iSortCol_0 );
logger.debug("sSortDir_0 == " + sSortDir_0 );
logger.debug("sSearch == " + sSearch );
try {
records = search.searchForAnEmployee(ssdh2,usertype,sSearch,"asc",
iSortCol_0,iDisplayStart,
iDisplayLength);
LinkedHashMap lhm= new java.util.LinkedHashMap();
lhm.put("sEcho", sEcho);
lhm.put("iTotalRecords",number_of_records);
lhm.put("iTotalDisplayRecords",9);
lhm.put("aaData",records);
// convert user object to json string, and save to a file
mapper.writeValue(new File("c:\\Downloads\\rstrh.json.txt"), lhm);
// display to console
logger.debug("My JSON: " + mapper.defaultPrettyPrintingWriter().writeValueAsString(lhm));
}
catch (Exception e) {
logger.debug("\n",e);
}
return lhm;
}// end function
I ran into the same warning as well, but the cause was different. I had null values in my data. The JSON format was correct, but DataTables does not know have a default rule for displaying nulls. The solution was to use the sDefaultContent property.
Sample aaData:
aaData: [
{ "Field1": "Foo", "Field2":null },
{ "Field1": "Bar", "Field2":null },
]
And then on the aoColumns, you can use the property as follows:
aoColumns: [
{ "mData": "Field1", sDefaultContent: "n/a" },
{ "mData": "Field2", sDefaultContent: "" }
]
This is not your current problem, but you may encounter this issue in the future.
Hope this was helpful.
I was having this same problem this morning. You need to have the aoColumns parameter and use mDataProp As in this:
https://gist.github.com/1660712
At least it solved my problem.
sDefaultContent option prevents displaying alert boxes only. Data tables wil not find the rule for displaying null values.
Changing null values in the table will eliminate this warning..
If it helps anyone I had a similar error because I had periods in my mRender function name:
My.Namespace.MyFunction(data, row);
This line:
var a = _fnSplitObjNotation( src );
Splits that into separate objects, which obviously generates an error.
Using
My_Namespace_MyFunction(data, row);
Additionally I noticed this error when passing a string function name instead of the JavaScript function object.
To avoid this error, your table number of "th" columns should equal to returning data columns(in numbers), in the above problem it is aaData.
"aaData" : [
[
"person_id" : "888888",
"ID" : "999999",
],
[
"person_id" : "8888889",
"ID" : "9999990",
]
]
This is correct format to return data from server side language.
I have solved my problem in same way.
Related
Bad JSON escape sequence: \\1. Path 'sections[0].facts[0].value', line 1, position 196."
Am getting getting Bad JSON escape sequence: \\1. Path 'sections[0].facts[0].value', line 1, position 196." while parsing json string with string.Format to add data based on placeholder. Below is the code : string jsonFormatString = #"{{""title"": ""{0}"",""sections"": [{{""facts"": [{{""name"": ""TransactionNo"",""value"": ""{1}""}}]}}]}}"; string formattedJson= string.Format(jsonFormatString , message, transactionNo ?? ""); var result = JsonConvert.DeserializeObject<dynamic>(formattedJson); The string values for placeholders were message = "Transaction Success", transactionNo = "1920\01\ABC"; Looks like escape character transactionNo field is creating problem. I tried with string.Replace(#"\\", #"\") and others nothing helped in resolving the error. If i added string.Replace(#"\", #"\\", it works but result json contains transactionNo as "1920\\01\\ABC" which is also wrong. Am i missing something or should i add anything more
I have seen folks do this in the past and even had to maintain code that looks like this... and as you are experiencing: It is a huge PITA. You can easily lay out your objects using anonymous types so they are simple to maintain and understand for the folks who may have the pleasure to work with your code in the future. Take a look at this: var myObj = new { title = "<input value>", sections = new[] { new { facts = new[] { new { name = "TransactionNo", value = "<input value>" } } } } }; var result = JsonConvert.SerializeObject(myObj, Formatting.Indented); Result will look like this: { "title": "<input value>", "sections": [ { "facts": [ { "name": "TransactionNo", "value": "<input value>" } ] } ] } Now, keep in mind that this is easier to maintain than formatting a string, but at the end of the day it's better to just bite the bullet and create some concrete models.
Parsing json : Test is json key existing
I'm request with API REST a JIRA filter since Excel and I return my result in a json object. I'm parsing this object and I Try to show my result (in a msgbox for now) but I have a problem when the json Key doesn't exist ! A extract of my json : { "expand":"schema,names", "startAt":0, "maxResults":500, "total":2, "issues":[ { "expand":"operations,versionedRepresentations,editmeta,changelog,renderedFields", "id":"00001", "fields":{ "components":[ { "id":"01", "name":"component_1" }, { "id":"02", "name":"component_02" } ] } }, { "expand":"operations,versionedRepresentations,editmeta,changelog,renderedFields", "id":"00002", "fields":{ "components":[ ] } }, ] } As you cans see, in my first issue (id 00001) I have a 2 components key but in my second issus (id 0002) I don't have component key, because this fields is empty in JIRA for this issue. So, a part of my code to show my result : For Each Item In jsonObject("issues") issueId = Item("id") compoId1 = Item("fields")("components")(1)("id") compoId2 = Item("fields")("components")(2)("id") i = i + 1 'PRINT_OF_MY_RESULT Next My problem : If my issue (00001) has a "component" value, it's OK and I can return my result but ... if my issus (00002) hasn't a result, my code failled to define compoId ... and my code crash. Did you have a simple solution ? I try somethings with Exists, isEmpty, etc etc ... but nothing concluent for me :(
You can modify your solution some what like this, For Each Item In jsonObject("issues") issueId = Item("id") For Each componentItem In jsonObject(Item("fields")("components")) If componentItem("id")==1 then compoId1 = componentItem("id") EndIf If componentItem("id")==1 then compoId2 = componentItem("id") EndIf Next i = i + 1 'PRINT_OF_MY_RESULT Next
Postman sending raw data
Im trying to send raw data to a web service I have. The service is waiting for a object named viaje which has the next data: * idDestino a numeric id * idLanta a numeric id * idPeticion an array of numeric ids * idVehiculo a numeric id Heres is what im trying out, but it wont even detect the index viaje. { "viaje" : [{ "idDestino" : 7, "idLlanta" : 7, "idPeticiones" : [{2,12]], "idVehiculo" : 1, }] } Im using laravel for the web services and here is how Im reciving the data. $object = Input::all(); $object = $object["viaje"]; //VARIABLES DE LOGIN INPUTS $idDestino = $object['idDestino']; $fechaInicio = date('Y-m-d H:i:s'); $idLlanta = $object['idLlanta']; $idPeticiones = $object['idPeticiones']; $idVehiculo = $object['idVehiculo']; what I want to know is how do I structure the raw data Im sending to fit the description I just gave. Also if doing this in form-data is possible how would I do this?
Ok I found out how to do the format for the json array: { "viaje" : { "idPeticiones": [ "1", "12" ], "idLlanta": 4, "idDestino": 7, "idVehiculo": 1 } } I was using {} an object instead of {} an array
How to get a specific value in this json
I have question, I hava a json with some information and I need to get a specific value, for example the Location, I had created a function but it doesn´t work fine, I get this error message about the " " SyntaxError: invalid label "location" : "Austin-Bergstrom International Airport, The function is this one function lee_json() { var temp = ('http://df9e7c46aa4c80573717-1199cc892ebab574a120721e4772cd8b.r11.cf2.rackcdn.com/services/aus.json'); temp2 = temp.location; alert(temp2); console.log(temp); console.log(temp.location); } and the Json is this one { "location" : "Austin-Bergstrom International Airport, Tx", "city" : "Austin", "state" : "Tx", "dewPointC" : 4.4, "visibilityMiles" : 10, "rainChance" : "10%" } What can be the problem ? Regards,
try this http://msdn.microsoft.com/en-us/library/ie/cc836466(v=vs.94).aspx this might be the kind of answer you're looking if i assume you are using jquery you can use this http://api.jquery.com/jQuery.getJSON/
Assuming 1) you are running this on the same domain where the json is hosted, 2) you have jquery, 3) the result is a json object, not an array, this is a legit example of getting a field: function getData(aLink) { $.getJSON(aLink, function(data) { console.log(data.location); }); } getData("http://df9e7c46aa4c80573717-1199cc892ebab574a120721e4772cd8b.r11.cf2.rackcdn.com/services/aus.json");
What is "compressed JSON"?
I see a lot of references to "compressed JSON" when it comes to different serialization formats. What exactly is it? Is it just gzipped JSON or something else?
Compressed JSON removes the key:value pair of json's encoding to store keys and values in seperate parallel arrays: // uncompressed JSON = { data : [ { field1 : 'data1', field2 : 'data2', field3 : 'data3' }, { field1 : 'data4', field2 : 'data5', field3 : 'data6' }, ..... ] }; //compressed JSON = { data : [ 'data1','data2','data3','data4','data5','data6' ], keys : [ 'field1', 'field2', 'field3' ] }; This method of usage i found here Content from link (http://www.nwhite.net/?p=242) rarely find myself in a place where I am writing javascript applications that use AJAX in its pure form. I have long abandoned the ‘X’ and replaced it with ‘J’ (JSON). When working with Javascript, it just makes sense to return JSON. Smaller footprint, easier parsing and an easier structure are all advantages I have gained since using JSON. In a recent project I found myself unhappy with the large size of my result sets. The data I was returning was tabular data, in the form of objects for each row. I was returning a result set of 50, with 19 fields each. What I realized is if I augment my result set I could get a form of compression. // uncompressed JSON = { data : [ { field1 : 'data1', field2 : 'data2', field3 : 'data3' }, { field1 : 'data4', field2 : 'data5', field3 : 'data6' }, ..... ] }; //compressed JSON = { data : [ 'data1','data2','data3','data4','data5','data6' ], keys : [ 'field1', 'field2', 'field3' ] }; I merged all my values into a single array and store all my fields in a separate array. Returning a key value pair for each result cost me 8800 byte (8.6kb). Ripping the fields out and putting them in a separate array cost me 186 bytes. Total savings 8.4kb. Now I have a much more compressed JSON file, but the structure is different and now harder to work with. So I implement a solution in Mootools to make the decompression transparent. Request.JSON.extend({ options : { inflate : [] } }); Request.JSON.implement({ success : function(text){ this.response.json = JSON.decode(text, this.options.secure); if(this.options.inflate.length){ this.options.inflate.each(function(rule){ var ret = ($defined(rule.store)) ? this.response.json[rule.store] : this.response.json[rule.data]; ret = this.expandData(this.response.json[rule.data], this.response.json[rule.keys]); },this); } this.onSuccess(this.response.json, text); }, expandData : function(data,keys){ var arr = []; var len = data.length; var klen = keys.length; var start = 0; var stop = klen; while(stop < len){ arr.push( data.slice(start,stop).associate(keys) ); start = stop; stop += klen; } return arr; } }); Request.JSON now has an inflate option. You can inflate multiple segments of your JSON object if you so desire. Usage: new Request.JSON({ url : 'url', inflate : [{ 'keys' : 'fields', 'data' : 'data' }] onComplete : function(json){} }); Pass as many inflate objects as you like to the option inflate array. It has an optional property called ’store’ If set the inflated data set will be stored in that key instead. The ‘keys’ and ‘fields’ expect strings to match a location in the root of your JSON object.
Based in Paniyar's answer, we can convert a List of Objects in "compressed" Json format using C# like this: var JsonString = serializer.Serialize( new { cols = new[] { "field1", "field2", "field3"}, items = data.Select(x => new object[] {x.field1, x.field2, x.field3}) }); I used an array of object because the fields can be int, bool, string... More Reduction: If the field is repeated very often and it is a string type, you can get compressed a little be more if you add a distinct list of that field... for instance, a field name job position, city, etc are excellent candidate for this. You can add a distinct list of this items and in each item change the value for a reference number. That will make your Json more lite.
Compressed: [["KeyA", "KeyB", "KeyC", "KeyD", "KeyE", "KeyF"], ["ValA1", "ValB1", "ValC1", "ValD1", "ValE1", "ValF1"], ["ValA2", "ValB2", "ValC2", "ValD2", "ValE2", "ValF2"], ["ValA3", "ValB3", "ValC3", "ValD3", "ValE3", "ValF3"], ["ValA4", "ValB4", "ValC4", "ValD4", "ValE4", "ValF4"]] Uncompressed: [{KeyA: "ValA1", KeyB: "ValB1", KeyC: "ValC1", KeyD: "ValD1", KeyE: "ValE1", KeyF: "ValF1"}, {KeyA: "ValA2", KeyB: "ValB2", KeyC: "ValC2", KeyD: "ValD2", KeyE: "ValE2", KeyF: "ValF2"}, {KeyA: "ValA3", KeyB: "ValB3", KeyC: "ValC3", KeyD: "ValD3", KeyE: "ValE3", KeyF: "ValF3"}, {KeyA: "ValA4", KeyB: "ValB4", KeyC: "ValC4", KeyD: "ValD4", KeyE: "ValE4", KeyF: "ValF4"}]
The most likely answer is that it really is just gzipped JSON. There is no other standard meaning to this phrase. Re-organizing a homogenous array of JSON objects into a pair of arrays is a very useful technique to make the payload smaller and to speed up encoding and decoding, it is not commonly called "compressed JSON". I haven't run across it ever in open source or any open API, but we use this technique internally and call it "jsontable".