JSON Data Map Issue with HighCharts + Ajax - ajax

I have the follow data returned via JSON
{"rows":[{"Date":"07/10/2011","Value":1206,"Action":"Drink"},
{"Date":"07/11/2011","Value":2288,"Action":"Pie"},
{"Date":"07/12/2011","Value":1070,"Action":"Drink"},
{"Date":"07/13/2011","Value":1535,"Action":"Beer"},
{"Date":"07/14/2011","Value":1721,"Action":"Drink"}],
"page":1,"total":1,"records":5}
I am trying to use this data with HighCharts but getting a bit confused.
jQuery.ajax({
url: fullPath + 'datamap',
dataType: "json",
type: 'POST',
data: "{}",
contentType: "application/json; charset=utf-8",
success: function (data) {
var lines = data.split('\n');
$.each(lines, function(lineNo, line) {
var items = line.split(',');
var data = {};
$.each(items, function(itemNo, item) {
if (itemNo === 0) {
data.name = item;
} else {
data.y = parseFloat(item);
}
});
options.series[0].data.push(data);
});
// Create the chart
var chart = new Highcharts.Chart(options);
},
cache: false
});
I am trying to chart "Date" and "Value" ?

As I understand you need to show rows values with Highcharts. So firstly your initial data will be:
var chartData = data.rows;
Now chartData is just an array of objects. Use for loop to iterate through chartData like below:
var seriesData = [];
for (var i = 0; i < chartData.length; i++)
{
var x = new Date(chartData[i].Date).getTime();
var y = chartData[i].Value;
seriesData.push([x, y]);
}
After this loop you will have seriesData array of points that can be used in Highcharts. Now just render it:
var chart = new Highcharts.Chart({
chart: {
renderTo: 'chartContainer',
defaultSeriesType: 'line'
},
xAxis: {
type: 'datetime'
},
series: [{
data: seriesData
}]
});
Voila!
Test this: http://jsfiddle.net/ebuTs/8263/

Related

Leaflet markers duplicating, removeLayer problem

I have Ajax function in my Laravel project. I'm taking data from db and send them on Leaflet map.
When I have setInterval, markers starts to duplicate. Unfortunately removeLayer can not help me, or I'm ussing it wrong.
This is my code
function callAjax() {
$.ajax({
url: '/device_new',
type: 'GET',
dataType: 'json',
success: function(data) {
markerLayer.removeLayer();
var markerLayer = L.featureGroup().addTo(map);
var coordinates = data;
for (var i = 0; i < coordinates.length; i++) {
if (coordinates[i].x && coordinates[i].y) {
marker = L.marker([coordinates[i].x, coordinates[i].y])
.bindPopup("Device: " + coordinates[i].device_type + '<br>' + "Time: " + coordinates[i].datetime)
marker.addTo(markerLayer);
}
}
map.fitBounds(markerLayer.getBounds());
},
});
setInterval(callAjax, 3000);
}
Any idea what could be a problem?
removeLayer(<Layer>) removes a single given layer from the featureGroup.
You need
markerLayer.clearLayers()
to remove all layers.
Change your code to:
function callAjax() {
$.ajax({
url: '/device_new',
type: 'GET',
dataType: 'json',
success: function(data) {
markerLayer.clearLayers();
var coordinates = data;
for (var i = 0; i < coordinates.length; i++) {
if (coordinates[i].x && coordinates[i].y) {
marker = L.marker([coordinates[i].x, coordinates[i].y])
.bindPopup("Device: " + coordinates[i].device_type + '<br>' + "Time: " + coordinates[i].datetime)
marker.addTo(markerLayer);
}
}
map.fitBounds(markerLayer.getBounds());
},
});
setInterval(callAjax, 3000);
}
function loadMap() {
// Where you want to render the map.
var element = document.getElementById('osm-map');
// Height has to be set. You can do this in CSS too.
element.style = 'height:405px;', 'width:500px;';
// Create Leaflet map on map element.
map = L.map(element);
// Add OSM tile leayer to the Leaflet map.
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
map.pm.addControls({
position: 'topleft',
});
//********************** ADD HERE **************
var markerLayer = L.featureGroup().addTo(map);
}

HighChart Pie Dynamic JSON in Codeigniter

Any help for this? The problem is I cannot get the data in pie. Any ideas? I tried to echo it outside the pie graph view, and the data appears in JSON as [{"Terminal":"13"}]. The Hightchart needs the data as ["Sample", 2]? Any suggestion sir on how to convert it like that? Thanks.
Heres my code:
VIEW
$(document).ready(function () {
$(function () {
var chart;
// Build the chart
$('.widget-lower-left#widget').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'Availability'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage}%</b>',
percentageDecimals: 1
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
showInLegend: true
}
},
series: [{
type: 'pie',
name: 'Availability',
data: []
}]
});
});
function requestData() {
$.ajax({
url: 'home',
datatype: "json",
success: function(data) {
alert(data);
console.log(data);
chart.series[0].setData(data);
},
cache: false
});
};
});
then in the MODEL
$results = $this->db->query("SELECT COUNT(get_jeeps_availability) as Terminal FROM get_jeeps WHERE get_jeeps_availability = 'Terminal'");
return $results->result_array();
in the CONTROLLER
public function index()
{
$data['pie'] = json_encode($this->get_model->dashboard_jeep_widget());
$this->load->view('home',$data);
}
In requestData() function, before setting data, preprocess 'data' that way:
var newData = [];
for( var i = 0, len = data.length; i < len; i++ ) {
var item = data[i];
for(var j in item){
newData.push([j,item[j]]);
}
}
chart.series[0].setData(newData);

Highcharts multiple series from json

My JSON looks like:
[[[773,1363709520],[774,1363709580]],[[1546,1363709520],[1548,1363709580]]]
I would like highcharts to create a new series every time it reaches a new JSON array: [[1546,1363709520],[1548,1363709580]]
I have a hard coded version, but making my data[[]] is not helping...
$(function () {
var data = [];
var data1 = [];
$.ajax({
url: "http://localhost:8080/vdm-stats-core/stats/metrics?from=2&src=org.example.fib&customer=customer0&server=server0&metric=responses.count",
dataType: "jsonp", // Notice! JSONP <-- P (lowercase)
jsonp: "callback",
success: function (inData) {
console.log(inData[0][1][0]);
var xval = new Date();
for (a = 0; a < inData.length; a++) {
for (i = 0; i < inData[a].length; i++) {
var yval = inData[a][i][0];
xval = inData[a][i][1];
var x = [xval, yval];
if (a == 0) {
data.push(x);
}
if (a > 0) {
data1.push(x);
}
}
}
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container'
},
title: {
text: 'Test',
},
rangeSelector: {
selected: 1
},
xAxis: {
type: 'datetime'
},
series: [{
name: 'Customer0',
data: data
}, {
name: 'Customer1',
data: data1
}]
});
},
error: function () {
console.log(arguments);
}
});
});
Please help!
I tried to understand your code, here's my intepretation;
function success(inData) {
var customerNr,
timestamp,
VALUE = 0,
TIMESTAMP = 1,
series = {},
len = inData.length,
yval,
item;
for (customerNr = 0; customerNr < len; customerNr++) {
// Init series object literal for customer
series[customerNr] = {
name : 'Customer '+customerNr.toString(),
data : []
};
// Setup data for customer
for (item = 0; item < inData[customerNr].length; item++) {
yval = inData[customerNr][item][VALUE];
timestamp = inData[customerNr][item][TIMESTAMP];
series[customerNr].data.push([timestamp,yval]);
}
// Add series, but redraw only on last customer
chart.addSeries(series[customerNr],customerNr===len-1);
}
};
You recycle the series object for each customer, but I've added a customerNr property. addSeries method in Highchart will by default redraw chart (http://api.highcharts.com/highcharts#Chart.addSeries()). I've selected to only redraw chart on last customer. Forked fiddle example at; http://jsfiddle.net/hkskoglund/VVLNV/
The important thing to keep in mind is that the series object is already a json object...
So the easiest thing to do, assuming you control the creation of the json file, is format the json output as the entire series object:
[{ name: 'Customer0', data: [[773,1363709520],[774,1363709580]] }, { name: 'Customer1', data: [[1546,1363709520],[1548,1363709580]] }]
and then:
series: myData
I got it to work:
Had to reset my series data.
$(function () {
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container'
},
title: {
text: 'Test',
},
rangeSelector: {
selected: 1
},
xAxis: {
type: 'datetime'
},
series: []
});
$.ajax({
url: "http://localhost:8080/vdm-stats-core/stats/metrics?from=200&src=org.example.fib&customer=customer0&server=server0&metric=responses.count",
dataType: "jsonp", // Notice! JSONP <-- P (lowercase)
jsonp: "callback",
success: function (inData) {
var xval = new Date();
var series = {
name: 'Customer',
data: []
}
for (a = 0; a < inData.length; a++) {
for (i = 0; i < inData[a].length; i++) {
var yval = inData[a][i][0];
xval = inData[a][i][1];
var x = [xval, yval];
series.data.push(x);
}
chart.addSeries(series);
series.data = [];
}
},
error: function () {
console.log(arguments);
}
});
});

MVC3 and Twitter Bootstrap TypeAhead without plugin

I have gotten TypeAhead to work properly with static data and am able to call my controller function properly and get data but it is either A: Not parsing the data properly or B: The TypeAhead is not set up correctly.
JavaScript :
<input type="text" id="itemSearch" data-provide="typeahead" value="#ViewBag.Item" name="itemSearch"/>
$('#itemSearch').typeahead({
source: function (query, process) {
parts = [];
map = {};
$.ajax({
url: '#Url.Action("MakePartsArray")',
dataType: "json",
type: "POST",
data: {query: query},
success: function (data) {
$.each(data, function (i, part) {
map[part.description] = part;
parts.push(part.description);
});
typeahead.process(parts);
}
});
},
updater: function (item) {
selectedPart = map[item].itemNumber;
return item;
},
matcher: function (item) {
if (item.toLowerCase().indexOf(this.query.trim().toLowerCase()) != -1) {
return true;
}
},
sorter: function (items) {
return items.sort();
},
highlighter: function (item) {
var regex = new RegExp('(' + this.query + ')', 'gi');
return item.replace(regex, "<strong>$1</strong>");
}
});
Controller :
public ActionResult MakePartsArray(string query)
{
var possibleItem = query.ToLower();
var allItems = Db.PartInventorys.Where(l => l.ItemNumber.Contains(possibleItem)).Select(x => new { itemNumber = x.ItemNumber, description = x.Description });
return new JsonResult
{
ContentType = "text/plain",
Data = new { query, total = allItems.Count(), suggestions = allItems.Select(p => p.itemNumber).ToArray(), matches = allItems, },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
In my controller I see the data being retrieved correctly and it appears to parse properly but nothing is showing up for my TypeAhead.
Any idea on how to verify exactly where the breakdown is occurring or does anyone see direct fault in my code?
Problem was in the ajax call-
$.ajax({
url: '#Url.Action("MakePartsArray")',
dataType: "json",
type: "POST",
data: {query: query},
success: function (data) {
$.each(data.matches, function (i, part) {
var composedInfo = part.description + ' (' + part.itemNumber + ')';
map[composedInfo] = part;
parts.push(composedInfo);
});
process(parts);
}
});
and in the controller on the return type
return new JsonResult
{
ContentType = "application/json",
Data = new { query, total = allItems.Count(), suggestions = allItems.Select(p => p.itemNumber).ToArray(), matches = allItems },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};

Needing example to load jqplot with multiple series, date-based data from json file

Been searching and cannot find exactly what I am looking for. Need to load multiple series into one jqplot, with each series coming from its own data file.
The example here http://www.jqplot.com/tests/data-renderers.php does show how to load a series from a file, but when I convert file to have date data, then it stops working, probably just a formatting issue, but cannot solve. What am I doing wrong?
Here is the data in the txt file:
[["7/11/2011 04:00:00am",85.0],["7/12/2011 04:00:00AM",87.4],["7/13/2011 04:00:00AM",90.0]]
Here is the code:
<script class="code" type="text/javascript">$(document).ready(function(){
var line = [ ];
var ajaxDataRenderer = function(url, plot) {
var ret = null;
$.ajax({
// have to use synchronous here, else returns before data is fetched
async: false,
url: url,
dataType:'json',
success: function(data) {
ret = data;
}
});
return ret;
};
var jsonurl = "./jsondata1.txt";
plo12 = $.jqplot('chart2', jsonurl,{
title: 'AJAX JSON Data Renderer',
dataRenderer: ajaxDataRenderer,
axes: {
xaxis: {
renderer:$.jqplot.DateAxisRenderer,
tickInterval: '1 day',
tickOptions:{formatString:'%y/%m/%d'}
}
}
});
});</script>
You could use the dataRendererOptions parameter to declare possible files, like this:
plo12 = $.jqplot('chart2', jsonurl,{
title: 'AJAX JSON Data Renderer',
dataRenderer: ajaxDataRenderer,
dataRendererOptions: {file1:'name_of_file_1', file2:'name_of_file2'}
axes: {
xaxis: {
Next use for-each to iterate trough the dataRendererOptions - Object:
var ajaxDataRenderer = function(url, plot,op) {
var ret = null;
$.each(op,function(i,n) {
$.ajax({
// have to use synchronous here, else returns before data is fetched
async: false,
url: url+'/'+i,
dataType:'json',
success: function(data) {
ret[]= data;
}
}); //end ajax
});//end each
return ret;
}
This code is not testet, but the idea behind could fit your needs.

Resources