jQuery datatables plugin databinding with string - javascript

I'm getting a JSON response from my service. Following the tutorial, I created response for binding data in datatables jquery plugin.
Client Side code :
var test_reports = jsonResp.reports;
var aDataSet = [test_reports];
$('#example').dataTable( {
"aaData": aDataSet,
"aoColumns": [{ "sTitle": "Tests" },
{ "sTitle": "Reports"}]
});
In console, my "test_reports" shows :
['TEST_1','1'] ['TEST_2','1']
But while binding this data to tables, it throws error. If I copy this cosole output into aaData, it creates the table. I understood that my "test_reports" is a string and this plugin is expecting an array of values. Any ideas of making this work!!
Server side code which gives this json response :
testcasesCountRS = statement.executeQuery(testcasesQuery);
while(testcasesCountRS.next()){
String test_name = testcasesCountRS.getString("test_name");
String test_count = testcasesCountRS.getString("test_count");
testResults.put(test_name, test_count);
resBuffer.append("[\'" + test_name + "\',\'" + test_count + "\'],");
}
resBuffer = resBuffer.deleteCharAt(resBuffer.lastIndexOf(","));
reports.put("reports", resBuffer);
Is there any alternative in my server side code to send the response as an array object to the datatables plugin.

You server response should be an array of array.
[['TEST_1','1'],['TEST_2','1']]
Change your code to
resBuffer.append("[");
while(testcasesCountRS.next()){
String test_name = testcasesCountRS.getString("test_name");
String test_count = testcasesCountRS.getString("test_count");
testResults.put(test_name, test_count);
resBuffer.append("[\'" + test_name + "\',\'" + test_count + "\'],");
}
resBuffer = resBuffer.deleteCharAt(resBuffer.lastIndexOf(","));
resBuffer.append("]");
The above code is untested. But hope you get the idea.
Documentation link

I made it work the following way :
JSONArray testCaseArray = new JSONArray();
while(testcasesCountRS.next()){
JSONArray testCase = new JSONArray();
String test_name = testcasesCountRS.getString("test_name");
String test_count = testcasesCountRS.getString("test_count");
testCase.add(test_name);
testCase.add(test_count);
testCaseArray.add(testCase);
}
reports.put("reports", testCaseArray);
The only thing thats bothering me is, it so stupid code that I need to create a new Array every time in my loop. And adding these arrays to my main Array object. There should be some work around to make it simple. Please suggest some efficient methodology.

Related

Custom query parameters format serializer and extractor [JS]

I have a JSON object of the type
[
{
at: "own",
op: "in_between",
va: ["str", "jan"]
},
{
a: 'alas',
op: 'cont',
va: [10, 20]
},
.
.
.
]
I want to pass this as a GET query parameter. Now I could just stringify it and pass it as something like this
?q={"0":{"at":"own","op":"in_between","va":["str","jan"]},"1":{"at":"alas","op":"cont","va":[10,20]}}
However I would prefer to serialize it in a different format. Something like
q[]=at:"own"|op:"in_between"|va:["str","jan"]&q[]=at:"alas"|op:"cont"|va:[10,20]
(I saw a this kind of format being used in Amazon's search filters. Any other format suggestions are welcome. My main goal is to shorten the URL)
So i was able to serialize it by just concatenating to a string
let q = "";
data.forEach(function(i) {
q = q.concat(`q[]=at:"${i.at}"|op:"${i.op}"|va:[${i.val}]&`);
});
return q.slice(0,-1);
Similarly I have an extractor
let qArray = q.split('&');
let qParse = [];
qArray.forEach(function(i) {
i = JSON.parse('{' + i.substring(4).split('|').join(',') + '}');
q.push(i);
});
However this only works well for q[1] where q[1]['va'] has an integer array. It needs to also work for q[0] with the string values
Also is there any better way of serializing and extracting it in these kinds of forms?
Thanks in advance!
As said previously in the comments, I was wondering if CSV wouldn't work for what you want. It's kind of easy to parse. Would this work (assuming filters is your array) ? :
let params = "?q=;at,op,va;";
filters.forEach(function(fil) {
params += fil.at + "," + fil.op + "," + JSON.stringify(fil.va) + ";";
})
If you want to store queries to make percentage, you'd just have to remove first three characters. I'm also supposing that all your dictionnaries follow the same structure. Hope this works for you

How to use json string after Serialization in view javascript?

I want to serialize a JSON string but when I pass JSON to view I see that my properties in code are in string format, that's probably why my code didn't work.
Serialization of my code in code behind:
var data = new ChartData
{
labels = new ChartLabels
{
labels = new string[3] {"Open", "Close", "Nothing"}
},
datasets = new ChartDatasets
{
data = new int[3] {20, 10, 3},
backgroundColor = new string[3] {"#ccf9d6", "#ccf9d6", "#ccf9d6"},
borderWidth = 1
}
};
var json = new JavaScriptSerializer().Serialize(data);
ScriptManager.RegisterStartupScript(
this,
GetType(),
"ServerControlScript",
"addChart(" + json + ");",
false);
And I want to use it in my JavaScript function:
function addChart(data) {
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, data);
EDIT:
Json looks like below:
{"labels":
{
"fontSize":0,
"boxWidth":0,
"labels":["Open","Close","Nothing"]},
"datasets":{"label":null,"data":[20,10,3],
"backgroundColor":["#ccf9d6","#ccf9d6","#ccf9d6"],
"borderWidth":1
}
}
Is there any way to convert it to correct format? Or just put it to a JavaScript variable?
As stated on MDN,
The JSON.parse() method parses a JSON string, constructing the
JavaScript value or object described by the string.
Seeing as the addChart javascript method call is being executed, but is getting a string instead of the expected JSON object, that string has to be parsed.
Without knowing the broader context of the application it is hard to give a great answer as there are a few ways you could accomplish your goal. The simplest though would be to change the line "addChart(" + json + ");", to "addChart(JSON.parse(" + json + "));", so that when the application executes this javascript, the json string will be parsed by the javascript engine and made into a javascript object the addChart method is expecting.
I am not hip to the ScriptManager and I kind of like things to appear as I expect when I do my debugging in Chrome so this is how I would attack it using an asp:Literal on the page.
ASP Page:
<script src="assets/js/bootstrap.js" type="text/javascript">
</script>
<asp:Literal runat="server" ID="aspchartdata"></asp:Literal>
Code Behind:
var data = new ChartData
{
labels = new ChartLabels
{
labels = new string[3] {"Open", "Close", "Nothing"}
},
datasets = new ChartDatasets
{
data = new int[3] {20, 10, 3},
backgroundColor = new string[3] {"#ccf9d6", "#ccf9d6", "#ccf9d6"},
borderWidth = 1
}
};
aspchartdata.Text = "<script> var data=" + JsonConvert.SerializeObject(data); + "</script>";
Now you have a data variable in Javascript to use.
On the server side your literal is replaced by your new script to define the variable and now you can handle the onload running and such from within the ASPX page in a neat fashion.

passing formatting JavaScript code to HighCharts with JSON

I have a website that uses AJAX to deliver a JSON formatted string to a HighCharts chart.
You can see this as the middle JSON code part at:
http://jsfiddle.net/1Loag7pv/
$('#container').highcharts(
//JSON Start
{
"plotOptions": {
"series": {"animation": {"duration": 500}}
,"pie": {
"allowPointSelect": true,
"cursor": "pointer",
"dataLabels": {"formatter":function(){return this.point.name+': '+this.percentage.toFixed(1) + '%';}}
}
},
"chart":{"renderTo":"divReportChart"}
,"title":{"text":"Sales Totals"}
,"xAxis":{"title":{"text":"Item"}, "categories":["Taxes","Discounts","NetSalesTotal"], "gridLineWidth":1}
,"yAxis":[{"title":{"text":"Amount"}, "gridLineWidth":1}]
,"series":[{"name":"Amount","type":"pie", "startAngle": -60,"yAxis": 0,"data":[["Taxes",17.8700],["Discounts",36.0000],["NetSalesTotal",377.9500]]}]
}
//JSON end
);
The problem is that the function part...
"dataLabels": {"formatter":function(){return this.point.name+': '+this.percentage.toFixed(1) + '%';}}
is not being transferred via the JSON
All research tells me that there is NO WAY to do this.
IE... Is it valid to define functions in JSON results?
Anybody got an idea on how to get around this limitation?
It is true that you cannot pass functions in JSON. Javascript is a superset of JSON.
A common approach is for the chart to be defined in javascript (e.g. during the page load), and the page then requests just the data via Ajax. When the data is returned it can be added to the chart object, either before it is rendered or afterwards using the highcharts API.
If you really want to pass the formatter function from the server with the chart, send it as a string, and then turn it into a function like this:
var fn = Function(mystring);
and use it in highcharts like:
chart.plotOptions.pie.dataLabels = {"formatter":fn};
I've re-factored your example to show the approach: http://jsfiddle.net/wo7zn0bw/
I had a similar conundrum. I wanted to create the JSON server side (ruby on rails) so I could create images of charts for a web API and also present it on the client web browser with the same code. This is similar to SteveP's answer.
To conform with JSON standards, I changed all formatter functions to strings
{"formatter": "function(){ return this.point.name+':'+this.percentage.toFixed(1) + '%';}"}
On the web side, I navigate the hash looking for formatter keys and replace them with the function using this code (may be a better way!?). javascript:
function HashNavigator(){
this.navigateAndReplace = function(hash, key){
if (!this.isObject(hash)){
//Nice if only navigated hashes and arrays
return;
}
var keys = Object.keys(hash);
for(var i = 0; i< keys.length; i++){
if (keys[i] == key){
//convert string to js function
hash[keys[i]] = this.parseFunction(hash[keys[i]]);
} else if (this.isObject(hash[keys[i]])){
//navigate hash tree
this.navigateAndReplace(hash[keys[i]], key);
} else {
//continue
}
}
};
this.isObject = function(testVar) {
return testVar !== null && typeof testVar === 'object'
}
//http://stackoverflow.com/questions/7650071/is-there-a-way-to-create-a-function-from-a-string-with-javascript
this.parseFunction = function(fstring){
var funcReg = /function *\(([^()]*)\)[ \n\t]*{(.*)}/gmi;
var match = funcReg.exec(fstring.replace(/\n/g, ' '));
if(match) {
return new Function(match[1].split(','), match[2]);
}
return null;
};
}
To use this, would be something similar to this javascript:
hashNavigator = new HashNavigator();
hashNavigator.navigateAndReplace(myHighchartsHash, "formatter")
At that point the hash/js-object is Highcharts ready
Similar idea was used for the web image API.
I was really hoping that hacking at the JSON was not the only solution, but it works!
I used a different approach. I created a JSON like below
{"formatter": "function(){ return this.point.name+':'+this.percentage.toFixed(1) + '%';}"}
When I came to evaluating the expression, I used (assuming that the value of the 'formatter' is formatterValueString)
formatterValueString = formatterValueString.replace('function()', '');
let opts = (new Function(formatterValueString)).call(this);
formatterValue = opts;
The reason to use this approach was it became hard to bind 'this' with the function. The eval() function did not go well with accessing variable this. I am sure there are ways to do it. Just thought this was quick.

How to encode cookie with javascript/jquery?

I am working on an online shop together with my friend. He set a cookie for me with PHP with the amount of added products to the Cart. The cookie is called "cart", and the variable with the amount of the products is called "items".
And I have to read the cookie and get the value of "cart" back with javascript and print it in the HTML document, but I have no Idea how to use it, can you please help me? I have never worked with cookies or JSON before, but I think it should be done with JSON, can you please explain it to me how it works?
when I do : console.log(document.cookie);
I receive something like this: cart=%7B%22items%22%3A%7B%228%22%3A1%7D%7D;
And I have no idea how to encode it.
Thank you
That is the URL encoded equivalent of {"items":{"8":1}} which is the JSON string you want.
All you have to do is decode it and parse the JSON:
var cart = JSON.parse(decodeURIComponent(document.cookie.cart));
Then logging cart should give you an object with an 'items' property that you can access as needed.
EDIT:
As an example, here's a way to iterate through the items and determine the total number of items and the total of all their quantities.
var items_total = 0,
quantity_total = 0;
for (var prop in cart.items) {
items_total += 1;
quantity_total += cart.items[prop];
}
console.log("Total Items: " + items_total);
console.log("Total Quantities: " + quantity_total);
Looks like you just need to decode it, then you will want to parse/eval it to get a workable object:
var obj, decoded = decodeURIComponent(document.cookie.cart);
if(window.JSON && JSON.parse){
obj = JSON.parse(decoded);
} else {
eval('obj = ' + decoded);
}
// obj == {"items":{"8":1}};

javascript arrays on gmaps

i'm newbie in javascript so, in this example exists the geometrycontrols.js (for global controls) and markercontrol.js (for marker controls)
my problem is identify the arrays where "data" is saved...
at the reference i see a savedata function but i have no idea how work with this function...
on the other side, in test.html if i've the outup on the Glog startup and output "data", and let me thinking that comes from array...
My objective is save the coordinates and other all atributes to mysql database, and when i discover where are "data" is the easy part.
if someone worked with this example (or not) can help me i'm grateful
ps: i'm really a newbie on javascript :P
edit1:
I was out for a time, and now I focus in geometrycontrols.js specially in: GeometryControls.prototype.saveData = function(opts){
var me = this;
if(opts.allData === true){
//me.saveAllData();
} else {
//construct a json data record
var geomInfo = opts.geomInfo, index = opts.geomInfo.index;
var record = geomInfo.storage[index];
var recordJSON = {};
recordJSON.type = record.type;
recordJSON.coordinates = [];
//determine geometry type, and copy geometry appropriately
if(record.type === "point"){
recordJSON.coordinates.push({lat:record.geometry.getLatLng().lat(),lng:record.geometry.getLatLng().lng()});
alert(recordJSON.coordinates);
} else {
alert("is not point");
var vertex;
for(var i=0;i<record.geometry.getVertexCount();i++){
vertex = record.geometry.getVertex(i);
recordJSON.coordinates.push({lat:vertex.lat(),lng:vertex.lng()});
}
}
//add title and description
recordJSON.title = record.title[0];
recordJSON.description = record.description[0];
//TODO add styles
recordJSON.style = ""; //TODO} //TODO Make separate prototype function?function postData(data){
//TODO
me.debug(data);
//alert(recordJSON.coordinates);
//alert(data);
};postData(me.serialize(recordJSON));}; `
When I alert(recordJSON.coordinates), the outupt is [object Object] and i've no idea why, in theory this array contains the coordinates...
Here is some code I have used to send the data to MySQL. It uses a little bit of jQuery to do the ajax magic (the line starting with the dollarsign is jQuery).
function postData(data){
me.debug(data);
var dataString = JSON.stringify(data);
me.debug(dataString);
$.post('storage.php', { data: dataString });
};
postData(recordJSON);
As you can see I've modified the way the 'recordJSON' object gets sent to the postData function a bit too: I've removed the serialise function.
Next, create a PHP file (called 'storage.php' in my case) and put this in it:
<?php
$received = json_decode($_POST['data'], true);
echo "just received " . $received['name'];
?>
You now have an array in PHP that you can do with as you please.
In the examplecode above I've modified the jQuery post function a bit, so if it doesn't work, look there.
The data is stored in JSON format in this file: http://gmaps-utility-library-dev.googlecode.com/svn/trunk/geometrycontrols/examples/data/testdata.js -- it's pretty much self-documenting, just follow the example to set your coordinates.
Note that if you need to find the latitude and longitude for a given address this is a good site: http://itouchmap.com/latlong.html

Categories

Resources