jqplot pass array uncaught exception: No Data - javascript

I am trying to pass the contents of an array to the jplot function but I am getting No data.
The array has been json encoden in php and it is an associative array.
$.ajax({
type: "POST",
url: "actions/myphp.php",
data: PassArray,
dataType: 'json',
beforeSend: function (html) { // this happens before actual call
// alert(html);
},
success: function (html) { // this happens after we get results
// $("#loginoutcome").text(html);
// alert(html);
var obj =html ;
// Now the two will work
$.each(obj, function(key, value) {
alert(key + ' ' + value);
});
var s1 = obj;
var plot8 = $.jqplot('pie8', [s1], {
grid: {
drawBorder: false,
drawGridlines: false,
background: '#ffffff',
shadow: false
},
axesDefaults: {},
seriesDefaults: {
renderer: $.jqplot.PieRenderer,
rendererOptions: {
showDataLabels: true
}
},
legend: {
show: true,
rendererOptions: {
numberRows: 1
},
location: 's'
}
});
I have also tried to pass it using var s1 = [obj]; but that didn't work also ...

This now works I was not using the array properly
success: function (html) { // this happens after we get results
// alert(html);
var obj =html ;
// Now the two will work
$.each(obj, function(key, value) {
alert(key + ' ' + value);
myArr.push([key, value]);
});
s1 = myArr;
var plot8 = $.jqplot('pie8', [s1], {
seriesColors: [ "#EB0712", "#12C456", "#EAA228", "#579575", "#839557", "#958c12",
"#953579", "#4b5de4", "#d8b83f", "#ff5800", "#0085cc"],
grid: {
drawBorder: false,
drawGridlines: false,
background: '#ffffff',
shadow: false
},
axesDefaults: {},
seriesDefaults: {
renderer: $.jqplot.PieRenderer,
rendererOptions: {
showDataLabels: true
}
},
legend: {
show: true,
rendererOptions: {
numberRows: 1
},
location: 's'
}
});
},

Related

pass the argument from one method to another method in extjs

This is my view part
Ext.define('A2a.view.act.Job', {
extend: 'Ext.container.Container',
requires: [
'A2a.store.Job',
'A2a.store.SharedData',
],
border: false,
chart: null,
hrer: [],
layout: {type: 'vbox', pack: 'start', align: 'stretch'},
initComponent: function () {
var me = this;
Ext.Ajax.request({
url: utils.createUrl('api', 'dashboard-read'),
async: true,
callback: function(opts, success, response) {
try {
if (success) {
var output = App.decodeHttpResp(response.responseText);
const data = output.data;
var myArr = [];
data.map((date) =>
myArr = Object.keys(date).filter(key => key != 'DATE'));
me.hrer =myArr;
console.log(me.hrer =myArr);
me.loadChart();
//me.loadww();
}
} catch (ex) {
//return ex;
}
}
});
this.loadww();
this.loadData(me.hrer);
me.callParent(arguments);
},
loadData : function () {
console.log("Init Function");
},
loadww: function (hrer) {
var me = this;
//var self = this;
console.log(me.hrer);
me.jobStore = Ext.create('O2a.store.PendingReports');
Ext.apply(me, {
items: [
{
xtype: 'chart',
itemId: 'charid',
name: 'charid',
store : new Ext.create('Ext.data.JsonStore', {
proxy: {
type: 'ajax',
url : utils.createUrl('api', 'dashboard-read'),
reader: {
type: 'json',
root: 'data'
}
},
autoLoad : true,
successProperty : 'success',
fields : [{name: 'DATE', type: 'auto'}].concat(
O2a.store.SharedData.hrer.map(function(companyName) {
console.log(companyName);
return {
name: companyName,
type: 'int'
};
})
)
}),
style: 'background: #fff',
insetPadding: 40,
animate: true,
shadow: false,
flex: 2,
minHeight: 300,
legend: {
position: 'top',
boxStrokeWidth: 0,
labelFont: '12px Helvetica'
},
axes: [{
type: 'Numeric',
position: 'left',
fields: ['1'],
grid: true,
minimum: 0,
}, {
type: 'Category',
position: 'bottom',
fields: ['DATE'],
grid: true,
}],
}]
});
},
loadChart: function (hrer) {
var me = this;
console.log(me.hrer);
var cha = this.down('#charid');
var iii = null;
Ext.Ajax.request({
url: utils.createUrl('api', 'dashboard-read'),
async: true,
callback: function(opts, success, response) {
try {
if (success) {
var output = App.decodeHttpResp(response.responseText);
const data = output.data;
me.hrer
let myArr = [];
data.map((date) =>
myArr = Object.keys(date).filter(key => key != 'DATE'));
cha.series.clear();
for(var i=0;i<myArr.length;i++){
cha.series.add({
type: 'line',
axis: 'left',
xField: 'DATE',
border: false,
flex: 1,
title: myArr[i],
yField: myArr[i],
markerConfig: {
radius: 4
},
highlight: {
fill: '#000',
radius: 5,
'stroke-width': 2,
stroke: '#fff'
},
tips: {
trackMouse: true,
style: 'background: #FFF',
height: 20,
width: 120,
renderer: function (storeItem, item) {
var name = item.series.title[Ext.Array.indexOf(item.series.yField, item.yField)];
this.setTitle(name + ': ' + storeItem.get(item.yField));
}
}
});
}
} else {
//return 'Unknown Reason';
}
} catch (ex) {
//return ex;
}
}
});
}
}
);
I want to pass the hrer inside the loadww method. If I call the loadww inside the callback of initcomponent function I can be able to pass it. But the graph is not loading. If I call it after the ajax request the graph is loading, but can't pass the hrer to outside.
How to pass the hrer array inside the loadww function. Thanks in advance
From the style of the code it looks like this is ExtJS 3.x
In Ext.Ajax.request define the scope with this to stay in the view.
Your code is not in the best shape.
get rid of the try...catch.
try to write success: this.dashboardSuccess
using callback, will run in both cases (success, failure)
If this is ExtJS 4+ you should split your code in MVC
If this is ExtJS 6+ you should split your code in MVVM
write your code declarative
out the stores in VM and use the load-Event
do not use initComponent
use data-binding

Ajax Calls in highchart.js

Hello there to all developers :-)
I want to ask a question about making Ajax Calls in the highchart.js library
I have some values which I am returning via Ajax based on the information I am giving to the back-end (its an MVC .NET project) and then I want to render a new chart in each div with the class gainChart (I am adding Ids for other purposes,so don't bother them :-) )
var iteratorJs = 0;
$(".gainChart").each(function (i) {
$(this).attr('id', "gainChart" + (i + 1));
var chart = new Highcharts.Chart({
chart: {
renderTo: this,
type: 'line',
margin: 0,
backgroundColor: 'rgba(255,255,255,0.3)'
},
colors: ['#2E5430'],
xAxis: {
lineWidth: 0,
minorGridLineWidth: 0,
lineColor: 'green',
//type: 'datetime',
labels: {
enabled: false
},
categories: [
$.ajax({
type: "POST",
url: "forex-copy-points-days",
data: { page: 0, perPage: 5, iterator: iteratorJs },
dataType: 'json',
async: false,
success: function (data) {
var daysArr = data.days;
JSON.stringify(daysArr);
categories = daysArr;
console.log(daysArr);
}
})
]
},
tooltip: {
formatter: function () {
var text = '';
text = this.y + '$';
return text;
}
},
credits: { enabled: false },
title: { text: null },
legend: {
enabled: false
},
plotOptions: {
series: {
stacking: 'normal',
pointWidth: 10
}
},
series: [{
name: 'Balance',
showInLegend: true,
legendMarkerColor: "green",
legendText: "Profit for account",
data: [
$.ajax({
type: "POST",
url: "forex-copy-points-balance",
data: { page: 0, perPage: 5, iterator: iteratorJs },
dataType: 'json',
async: false,
success: function (balances) {
var balArr = balances.balances;
JSON.stringify(balArr);
data = balArr;
console.log(balArr);
}
})
]
}],
exporting: {
enabled: false
},
responsive: {
rules: [{
condition: {
maxWidth: 600
},
chartOptions: {
legend: {
enabled: false
}
}
}]
}
});
iteratorJs++;
});
The returning data is as it is supposed to be (different strings), yet nothing is displayed - only the background of the chart. Can someone give me a clue how to solve this and what to change in order to solve my problem.
Thanks in advance!
The jQuery $.ajax method call doesn't return the data that results from this call, so you can't write myData = $.ajax(). You have to use the success callback to get the data, and then use it.
So for example, instead of writing this:
categories: [
$.ajax({
type: "POST",
url: "forex-copy-points-days",
data: { page: 0, perPage: 5, iterator: iteratorJs },
dataType: 'json',
async: false,
success: function (data) {
var daysArr = data.days;
JSON.stringify(daysArr);
categories = daysArr;
console.log(daysArr);
}
})
]
You should write something like this:
$.ajax({
type: "POST",
url: "forex-copy-points-days",
data: { page: 0, perPage: 5, iterator: iteratorJs },
dataType: 'json',
async: false,
success: function (data) {
// create graph from AJAX call results
var chart = new Highcharts.Chart({
xAxis: {
categories: JSON.stringify(data.days)
},
series: [{
data: JSON.stringify(balances.balances)
}]
});
}
});

high chart total data

I try to populate chart when user click on button .. and chart is display like this
now the problem i want total i.e. as in image in red circle i write TOTAL : 3 .. 3 is beacuse 2 for MV and 1 for DSB so total is 3
I try this
this is the code which i try
<script type="text/javascript">
var strArray = "[['sfdsdfLi', 9],['Kiwsdfi', 3],['Mixesdfd nuts', 1],['Oranges', 6],['Grapes (bunch)', 1]]";
$(function () {
$('#tabledata').on('click', 'tr', function () {
var row = $(this);
var Id = row.find('td')[0].firstChild.data;
var obj = {};
obj.ID = Id;
GetData(obj);
return false;
});
});
function GetData(obj) {
$.ajax({
type: "POST",
url: "WebForm1.aspx/GetVo",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (result) {
if (result !== null && result.length == 0) {
$("#cont").hide();
return;
}
strArray = result.d;
var myarray = eval(strArray);
$("#cont").show();
$('#cont').highcharts({
chart: {
borderColor: 'Grey',
borderWidth: 2,
type: 'pie',
options3d: {
enabled: true,
alpha: 45
}
},
title: {
text: 'Data1'
},
position: {
align: 'right',
verticalAlign: 'bottom',
x: 10,
y: -10
},
subtitle: {
text: '3D Chart'
},
plotOptions: {
pie: {
innerSize: 100,
depth: 45,
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.y}',
},
showInLegend: true
}
},
series: [{
name: 'Delivered amount',
data: myarray
}]
});
},
error: function (error) {
alert(error);
}
});
}
</script>
now how i get total ? any solutions

Get Data Using Ajax Jquery and send Parameters to Controller

I have a method that get data from database and show it on chart. Its working fine. Now, i need to put some filters on it, and I'm facing dificulties to pass my parameters to the controller.
$("#quadro").click(function () {
Highcharts.setOptions({
lang: {
decimalPoint: ',',
thousandsSep: '.'
}
});
var data1 = $('#data1').val();
var data2 = $('#data2').val();
var empresa = $('#empresa option:selected').text();
$.ajax({
url: 'Painel/QuadroReceitas',
dataType: "json",
type: "GET",
contentType: 'application/json; charset=utf-8',
data: { 'data1': data1, 'data2': data2, 'empresa': empresa },
async: false,
processData: false,
cache: false,
delay: 15,
success: function (data) {
var Categories = new Array();
var FaturadoArray = new Array();
var RecebidoArray = new Array();
var AtrasadoArray = new Array();
for (var i in data) {
Categories.push(data[i].Mes);
FaturadoArray.push(data[i].Receitas);
RecebidoArray.push(data[i].Recebido);
AtrasadoArray.push(data[i].Inad_Atual);
}
var MesArray = JSON.parse(JSON.stringify(Categories));
quadroReceitas(MesArray, FaturadoArray, RecebidoArray, AtrasadoArray);
},
error: function (xhr) {
alert('error');
}
});
});
function quadroReceitas(MesArray, FaturadoArray, RecebidoArray, AtrasadoArray) {
var GlobalRotation = -90;
var GlobalAlign = 'right';
var X;
var Y;
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'column',
realignLabels: true,
animation: false
},
title: {
text: 'Quadro de Receitas'
},
legend: {
align: 'left',
verticalAlign: 'top',
floating: true,
x: 0,
y: 0
},
xAxis: {
categories: MesArray,
crosshair: true,
},
yAxis: {
labels: { enabled: false },
title: { enabled: false },
},
credits: {
enabled: false
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
'<td style="padding:0"><b>{point.y:,.1f}</b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
column: {
animation: true,
pointPadding: 0.05, // Defaults to 0.1
groupPadding: 0.05, // Defaults to 0.2
dataLabels: {
enabled: true,
rotation: GlobalRotation,
color: '#FFFFFF',
align: GlobalAlign,
verticalAlign: "top",
y: 10,
inside: false,
crop: false,
style: {
fontSize: '12px',
fontFamily: 'Verdana, sans-serif'
},
formatter: function () {
return Highcharts.numberFormat(this.y, 2);
}
}
},
},
series: [
{ name: 'Faturado', color: '#004a91', data: FaturadoArray },
{ name: 'Recebido', color: '#009147', data: RecebidoArray },
{ name: 'Atrasado', color: '#FF0000', data: AtrasadoArray }
]
});
}
On Controller i have the code as bellow:
[HttpGet]
public JsonResult QuadroReceitas(string data1, string data2, string empresa)
{
if(empresa == "empresa" || empresa == null)
{
empresa = "%";
}
//Chave oChave = new Chave();
DateTime agora = DateTime.Now;
var start = new DateTime(agora.Year, agora.Month, 1).AddMonths(-11);
var end = new DateTime(agora.Year, agora.Month, 1).AddMonths(1).AddDays(-1);
if (data1 == null)
data1 = start.ToShortDateString();
if (data2 == null)
data2 = end.ToShortDateString();
ContasReceberData recData = new ContasReceberData();
List<ContasReceber> receitas = new List<ContasReceber>();
receitas = recData.GetQuadroReceitas(data1, data2, empresa)
.Select(o => new ContasReceber
{
Mes = o.Mes,
Receitas = Math.Round(o.Receitas,2),
Recebido = Math.Round(o.Recebido, 2),
Inad_Atual = Math.Round(o.Inad_Atual, 2)
}).ToList();
return Json(receitas, JsonRequestBehavior.AllowGet);
}
As I told, it is working fine, but without the parameters:
data1, data2, empresa
I tried to change on AJAX to POST and Controller to HttpPost as i read in another topic but didnt work.
Because in your ajax method you set processData=false. set it to true or delete the line of processData and it's work!
var empresa = $('#empresa option:selected').text();
$.ajax({
url: 'Painel/QuadroReceitas',
dataType: "json",
type: "GET",
contentType: 'application/json; charset=utf-8',
data: { 'data1': data1, 'data2': data2, 'empresa': empresa },
async: false,
// processData: false,
cache: false,
delay: 15,
success: function (data) {
var Categories = new Array();
var FaturadoArray = new Array();
var RecebidoArray = new Array();
var AtrasadoArray = new Array();
for (var i in data) {
Categories.push(data[i].Mes);
FaturadoArray.push(data[i].Receitas);
RecebidoArray.push(data[i].Recebido);
AtrasadoArray.push(data[i].Inad_Atual);
}
var MesArray = JSON.parse(JSON.stringify(Categories));
quadroReceitas(MesArray, FaturadoArray, RecebidoArray, AtrasadoArray);
},
error: function (xhr) {
alert('error');
}
});
});

Why my global variable isnt modified inside a JavaScript callback function

I want to modify json object inside a function and then use the received value at another function. This is as a glimpse what I've coded:
$(document).ready(function () {
var json
$("#ok").click(function(){
function plotReglaFalsa(respuesta) {
json = respuesta
}
....
....
plotReglaFalsa(anyJSON)
function populateTable () {
console.log(json)
}
populateTable()
})
However json is not being modified, I do call functions required to the to the point of json being modified and the console.log statement prints undefined. I also know respuesta is a valid object.
However, plotReglaFalsa is actually a callback argument in an AJAX request, this is my full code:
$(document).ready(function () {
var json
$.plot($("#placeholder"), [ [] ], { yaxis: { show: true, max: 100, min: -100 }, xaxis: { show: true, max: 100, min: -100} });
$("#ok").click(function(){
var args = { algorithm: 'ReglaFalsa.py',
parameters: "\'"+$("#fx").val() + "\' " +
$("#a").val() + " " +
$("#b").val() + " " +
$("#tolerancia").val() + " " +
$("#iteracionesMaximas").val()
}
function plotReglaFalsa(respuesta) {
json = respuesta
var result = []
for (var series in respuesta) {
if (series!="x" && series != "y")
result.push({
data : [ [respuesta[series].a,respuesta[series].F], [respuesta[series].b, respuesta[series].G]]
})
}
result.push({
label: "fx",
color: "#FB2365",
data: _.zip(respuesta['x'], respuesta['y'])
})
var plot = $.plot( $("#placeholder"),
result,
{ selection:{mode: "xy"},
zoom: { interactive: true },
pan: { interactive: true },
grid: { markings: [{ xaxis: { from: 0.0, to: 0.0 }, color: 'black', lineWidth: 1 }, { yaxis: { from: 0.0, to: 0.0 }, color: 'black', lineWidth: 1 }] }
})
plot.getOptions().selection.mode = null
}
getSendingJSON("/plot",args,plotReglaFalsa)
populateTable()
function populateTable () {
console.log(json)
$("body").append("<table id='resultados' class='table table-bordered'><thead><th>i</th><th>a</th><th>F</th><th>b</th><th>G</th><th>w</th></thead><tbody></tbody></table>")
$('#resultados').dynatable({
features: {
paginate: false,
sort: false,
search: false,
perPageSelect: false,
recordCount: false
},
dataset: { records: json }
})
}
})
})
And this is populate table function:
function getSendingJSON(url,reqObject,callBack) {
$.ajax({
type: "get",
data: reqObject,
dataType: "json",
url: url,
success: function(response){
callBack(response);
}
});
}
Understanding that the issue is around the AJAX nature, what's the easiest workaround to assign response to a variable?

Categories

Resources