JSON, Highcharts and Coldfusion json data - javascript

I have been trying to make this work for sometime and its I cannot seem to find the solution to make this work.
I am able to output JSON with my coldfusion CFC without issue, not I am trying to use this JSON with Highcharts.js. I have verified that the JSON is valid but highcharts seems to have an issue because in the series data there is double quotes surrounding the data. I've looked everywhere for a solution and I cannot seem to find any help that can set me on the right path. If I remove the double quotes from around the array in the series.data the chart loads in fine but I get away from it being dynamic.
Here is my JSON output from my CFC:`
{
"series": [{
"data": "[[Date.UTC(2017,05,21),2.9],[Date.UTC(2017,05,28),2.9],[Date.UTC(2017,06,04),3.1],[Date.UTC(2017,06,11),2.9]]",
"name": "ATC Main Pod A - B - C"
}, {
"data": "[[Date.UTC(2017,05,21),2.8],[Date.UTC(2017,05,28),2.6],[Date.UTC(2017,06,04),2.9],[Date.UTC(2017,06,11),2.9]]",
"name": "ATC Mays (ACB Blue)"
}, {
"data": "[[Date.UTC(2017,05,21),2.4],[Date.UTC(2017,05,28),2.6],[Date.UTC(2017,06,04),3],[Date.UTC(2017,06,11),3.2]]",
"name": "ATC Mays (ACB Purple)"
}, {
"data": "[[Date.UTC(2017,05,21),3.3],[Date.UTC(2017,05,28),3.3],[Date.UTC(2017,06,04),3.4],[Date.UTC(2017,06,11),3.3]]",
"name": "ATC R10 Pod D"
}, {
"data": "[[Date.UTC(2017,05,21),3.3],[Date.UTC(2017,05,28),3.4],[Date.UTC(2017,06,04),2.8],[Date.UTC(2017,06,11),1.9]]",
"name": "ATC TU Pod A - B"
}, {
"data": "[[Date.UTC(2017,05,21),2.9],[Date.UTC(2017,05,28),2.9],[Date.UTC(2017,06,04),3.1],[Date.UTC(2017,06,11),3.4]]",
"name": "CTRC 1st Floor"
}, {
"data": "[[Date.UTC(2017,05,21),2.9],[Date.UTC(2017,05,28),3.3],[Date.UTC(2017,06,04),3.2],[Date.UTC(2017,06,11),2.3]]",
"name": "CTRC 2nd Floor"
}]
}
Here is what my ajax call looks like:
function loadChartData(c){
$.ajax({type: "POST", url: "CFCs/survey.cfc", data: {method:"results_RLU", CENTERID: c},dataType: 'json',success: function(data){
options.series = data.series
var chart = new Highcharts.Chart(options)
}
});
}

Not a problem!
Simply iterate each item in the series and parse the data to valid JSON object.
Enjoy :)
function loadChartData(c){
$.ajax({type: "POST", url: "CFCs/survey.cfc", data: {method:"results_RLU", CENTERID: c},dataType: 'json',success: function(data){
options.series = data.series.map(function(item)
{
item.data = JSON.parse(item.data);
return item;
});
var chart = new Highcharts.Chart(options)
}
});
}

Related

How to retrieve data from json file

I am having trouble with accessing my json file from my javascript file. I would like to change the object to a different text in my json file once a submit button is clicked on the webpage. I am aware that I would use ajax to achieve this goal, but I do not know how to access the json file.
This is the db.json file
{
{
"assets": [
{
"id": "0946",
"manufacturer": "SONY",
},
{
"id": "0949",
"manufacturer": "AUDIOTECNIA"
}
],
"transfers": [
{
"id": 1,
"status": "in-progress"
}
]
}
This is my Javascript file
$('form').on('submit', function(e){
e.preventDefault();
parsedData = JSON.parse(db.json);
console.log(parsedData[0].id)
//Changing Status
$.ajax({
type: "PATCH",
url: `http://localhost:3000/transfers/`
});
I've tried using parseData because I read that is how to retrieve the object, from the json file, but I do not believe I am writing it correctly. What documentation or steps would one recommend for solving this issue?
You have an extra comma after "in-progress",
const parsedData = JSON.parse(`{
"transfers": [ {
"id": 1,
"status": "in-progress"
}]
}`)
Then, to access id in parsedData:
console.log(parsedData.transfers[0].id)
You did not initialize the variable parsedData.
var parsedData = JSON.parse(db.json);

Return JSON results as JS array with AJAX?

Apologies in advance - I am new to this and so other answers have not been able to help me.
I have used AJAX to send data to a PHP script (part of a 3rd party API). The PHP script returns the results as JSON, but I have no idea how to format these on my HTML page.
Ultimately, I would like to save the JSON results as an array and then use JS/Jquery to format them on the page.
I am not sure how to modify the PHP and AJAX scripts to achieve this. Can anyone point me in the right direction?
My AJAX:
$.ajax({
type: 'POST',
url: 'calculator.php',
data: {toPostcode: toPostcodeValue, parcelLengthInCMs: parcelLengthInCMsValue, parcelHeighthInCMs: parcelHeighthInCMsValue, parcelWidthInCMs: parcelWidthInCMsValue, parcelWeightInKGs: parcelWeightInKGsValue},
success: function(data) {
<!--NOT SURE WHAT TO PUT HERE-->
}
})
PHP (after the calculator does its thing - not sure if it needs to be changed):
$serviceTypesJSON = json_decode($rawBody);
echo json_encode($serviceTypesJSON);
The expected JSON results should look like:
{
"services": {
"service" : [
{
"code": "AUS_PARCEL_REGULAR",
"name": "Parcel Post (your own packaging)",
"speed": 2,
"price": 6.95,
"max_extra_cover": 5000,
"extra_cover_rule": "100,1.5,1.5",
"icon_url": "http://test-static.npe.auspost.com.au/api/images/pac/regular_post_box.png",
"description": "Based on the size and weight you've entered",
"details": "Check our ",
"delivery_time": "Delivered in up to 3 business days",
"ui_display_order": 1,
"options": {
"option": [
{
"code": "AUS_SERVICE_OPTION_STANDARD",
"name": "Standard Service",
"price": "0.00",
"price_type": "static",
"option_type": "optional",
"ui_display_order": 1
},
{
"code": "AUS_SERVICE_OPTION_SIGNATURE_ON_DELIVERY",
"name": "Signature on Delivery",
"price": 2.95,
"price_type": "static",
"option_type": "optional",
"tooltip": "Signature on Delivery provides you with the peace of mind that your item has been delivered and signed for.",
"ui_display_order": 2,
"suboptions": {
"option": {
"code": "AUS_SERVICE_OPTION_EXTRA_COVER",
"name": "Extra Cover",
"option_type": "optional",
"price_type": "dynamic",
"tooltip": "Extra Cover provides cover for loss, damage or theft of your item and will fully compensate you to the value specified for your item.",
"ui_display_order": 1
}
}
}
]
}
},
You can do two things, if the return data is JSON use dataType: "json" in the AJAX call.
Edit 1
If you are using dataType: "json". Which is more preferred if you are sure the data return is JSON string. data variable in the success will directly give you the JSON object. I think you can access it like data['services'].
success: function (data) {
jsonObj = $.parseJSON(data);
//this gives you the inner onject of the return data
servicesObj = jsonObj.services;
}
Or you can just get the data then use jQuery.parseJSON() to parse the data string into JSON object.
$.ajax({
type: 'POST',
url: 'calculator.php',
data: {
toPostcode: toPostcodeValue,
parcelLengthInCMs: parcelLengthInCMsValue,
parcelHeighthInCMs: parcelHeighthInCMsValue,
parcelWidthInCMs: parcelWidthInCMsValue,
parcelWeightInKGs: parcelWeightInKGsValue
},
success: function (data) {
jsonObj = $.parseJSON(data);
//this gives you the inner onject of the return data
servicesObj = jsonObj.services; //or jsonObj["services"]
}
})
Your success function will never be called if you are using
echo json_encode(); in your php script.
You should add dataType:'json' after type:'POST' and then your success function will get called and will get the result returned by server in data

Zingcharts live feed not rendering chart

So I have been trying out ZingCharts which in general I like a ton. But now I am trying to create a live feed and the documentation isn't all that clear. I am trying to use HTTP to update a chart with new values. It seems that I need to have a page that is sending the chart data with updated values and that is what I am doing. This chart renders correctly when I past the JSON directly in the browser but not as a live feed, it now only emphasized textcorrectly pulls from the /metrics_feed and renders the outline of the chart but it is all grey. The JSON I am sending over HTTP is:
{
"crosshair-x": {},
"legend": {},
"plot": {
"valueBox": {
"placement": "top",
"type": "max, min",
"visible": false
}
},
"scaleX": {
"label": {
"text": "Metric count"
}
},
"scaleY": {
"label": {
"text": "Metric value"
}
},
"series": [
{
"text": "data point",
"values": [
-4.69283003950355,
-4.692830039503548,
-4.6928300395035505
]
}
],
"title": {
"text": "metrics over time"
},
"tooltip": {},
"type": "line"
}
And I am planning to update those values every second or so. Here is my HTML side code:
<head>
...
<script type="text/javascript">
var myChart = {"refresh":{
"type":"feed",
"transport":"http",
"url":"/metrics_feed",
"interval":1000
}
};
window.onload=function(){
zingchart.render({
id:"myChartDiv",
data:myChart,
height:600,
width:"100%"
});
};
</script>
</head>
<body>
<div id="myChartDiv"></div>
</body>
And this all works when I copy the direct JSON in there instead of sending it over HTTP so there is something I am missing in the Zingcharts documentation I suppose.
I'm on the ZingChart support team, and I'm happy to help you figure this out. You'll want to configure most of your chart settings and objects in your page, so in the myChart object. That means crosshair-x, legend, plot, etc... should all be static in the page and not passed via HTTP. In the JSON object, create empty series objects within the series array for each series that you will be passing to the chart. So, if you will only have one series plotted:
{
"type": "line",
"title": {
"text": "metrics over time"
},
/* Additional objects (tooltip, legend, crosshair, etc...) omitted for brevity */
"series": [
{
"values": []
}
]
}
And if you will be passing 2 series values:
{
"type": "line",
"title": {
"text": "metrics over time"
},
/* Additional objects (tooltip, legend, crosshair, etc...) omitted for brevity */
"series": [
{
"values": []
},
{
"values": []
}
]
}
The "refresh" object should also be placed in the myData object, in the top level:
{
"type": "line",
"title": {
"text": "metrics over time"
},
/* Additional objects (tooltip, legend, crosshair, etc...) omitted for brevity */
"refresh":{
"type":"feed",
"transport":"http",
"url":"/metrics_feed",
"interval":1000
},
"series": [
{
"values": []
},
{
"values": []
}
]
}
Depending on how many series objects you want in your chart, configure your script to pass values in the following format:
[ { "plot0" : 27, "plot1" : 34 } ]
Here's the feeds.php script that we use for the chart under the HTTP section of our feeds article:
<?php
$min = isset($_GET['min'])?intval($_GET['min']):0;
$max = isset($_GET['max'])?intval($_GET['max']):50;
$plots = isset($_GET['plots'])?intval($_GET['plots']):1;
?>
[
{
<?php
for ($plot=0;$plot<$plots;$plot++) {
?>
"plot<?php echo $plot; ?>" : <?php echo rand($min, $max); ?>,
<?php
}
?>
"scale-x" : "<?php echo date('H:i:s'); ?>"
}
]
This script also returns a timestamp that gets injected to an empty values array in our scale-x object. You can see a sample response here.
I apologize if our docs did not make this clear, I'll be updating them with added clarification soon. Anyway, I hope that helps you! Let me know if you need some more help.

How to get jstree to work properly with ajax loaded content

For a project I am trying to create an ajax-powered treeview control. My ajax scripts are working fine on the back end, but the tree is not being displayed properly. When I hard code the ajax response into my tree container, it is displayed properly:
However, when I try to load the tree via ajax I get this:
Here is my JS code:
$(document).ready(function() {
function customMenu(node) {
var items = {
createItem : {
label : "Generate random number(s)",
action: function() {
console.log("Creating children...");
var selectedId = $("#treeview").jstree("get_selected").attr("id");
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "libs/add.php",
data: "fact_id=" + selectedId,
dataType: "json",
success: function(data) {
console.log(data);
}
});
}
}
}
return items;
}
$("#treeview").jstree({
"plugins" : ["themes", "html_data", "ui", "crrm", "contextmenu"], contextmenu: {items: customMenu, select_node: true}
});
$.ajax({
url: "libs/display.php",
dataType: "json"
}).success(function(data) {
$("#treeview ul").append(data);
});
});
Does anyone have any idea what my problem is? Any help would be appreciated.
EDIT
After looking closer, I realize that the exact problem is that the necessary classes are not being added to the child nodes when calling via ajax. Still, I'm not sure why.
ANOTHER EDIT
display.php now contains this response text:
[
{
"attr": {
"id": 1
},
"data": 649,
"state": "closed"
},
{
"attr": {
"id": 1
},
"data": 108,
"state": "closed"
},
{
"attr": {
"id": 1
},
"data": 86,
"state": "closed"
},
{
"attr": {
"id": 1
},
"data": 46,
"state": "closed"
}
]
Am I headed in the right direction?
Is your stylesheet being included, and have you set up correct URLs to the icons? It looks to me like that's why your data isn't being styled. However, looking at your code, a more likely reason that you aren't getting your styling is because you are just calling an arbitrary AJAX call outside the jsTree scope.
Take a look at the docs for the json_data plugin for jsTree. It's easy to use, provided you set up display.php correctly to only fetch the node that jsTree is requesting. It will make concurrent calls and get the nodes it needs, your script simply needs to serve them to it:
$("#treeview").jstree({
"plugins" : ["themes", "html_data", "ui", "crrm", "contextmenu"],
"contextmenu": {
items: customMenu,
select_node: true
},
"json_data": {
"ajax": {
"url": "libs/display.php",
"data": function(n) {
return { id : n.attr ? n.attr("id") : 0
}
}
}
});
The json_data plugin basically acts as a wrapper for a jQuery AJAX call, but the events are bound directly the jsTree core and the returned results are handled by jsTree. You'll probably need to tweak your return values a bit depending on what display.php is responding with, and what you have set your tree up to look like structurally.
Edit
This is a similar post that might help you:
jsTree and AJAX > Load all data via ajax

display json data using xhrget (DOJO)

I am unable to figure out what is the problem with displaying json data..below is the code
var xhrGet1 = dojo.xhrGet({
url: "Page/",
handleAs: "json",
handle: function(response)
{
dojo.byId('json-data').innerHTML = response.questions[0];
}
});
Html
<div id='json-data'></div>
And my json file looks like this
{
"Info": {
"PURPOSE": ".... ",
},
"questions": [
{
"ID": 1,
"Question": "User ID",
"Information": "",
}, {
"ID": 2,
"Question": "Name",
"Information": "",
}
],
so on...any ideas??
The property handleAs : "json" in your xhr call makes the incoming json automatically eval'ed to javascript objects. So, you have to convert your javascript object back to string using JSON.stringify.
e.g. :
dojo.byId('json-data').innerHTML = JSON.stringify(response.questions[0]);
You can also use dojo.toJson for the same purpose. It uses json.stringify but has the benefit of having a second argument ("prettyprint"), allowing you to pretty-print out of the box, like this :
dojo.byId('json-data').innerHTML = dojo.toJson(response.questions[0], true);
wrap your JSON with PRE and CODE tags.
So:
dojo.byId('json-data').innerHTML = "<pre>code>" + response.questions[0] + "</code></pre>";
Also see: Display JSON as HTML for some libraries that can help you pretty-format your JSON when rendering in the browser

Categories