I am trying to post a ajax request to my server.js script in node js. The script then passes the data from the ajax request to the stored procedure and is supposed to return the result to the ajax function. But for some reason, I am getting an undefined error while debugging my ajax function. What could I be doing wrong?
plain.ejs
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.3.min.js" ></script>
<script src="http://code.highcharts.com/highcharts.js" ></script>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>
<div id="container1" style="width:100%; height:400px;"></div>
<div id ="container2" style="height:20px;"></div>
<div id ="container3" style="width:100%; height:400px;"></div>
<script type="text/javascript">
$(document).ready(function () {
var bankid = [ 57, 9912, 9905, 16, 58 ];
var country = ["KENYA", "KENYA", "KENYA", "UGANDA", "UGANDA"];
var counter = 0;
var merchantname = [];
var successtranscs = [];
var failedtranscs = [];
var servicetranscs = [];
var bankname;
var rows =<%-JSON.stringify(Resultset)%>
function initfunc() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/dashboard",
data: JSON.stringify({country: country[counter], bankid: bankid[counter]}),
dataType: "json",
success: function (Result) {
Result = Result.d;
console.log("result" +Result);
var data = [];
var merchantname = [];
var successtranscs = [];
var failedtranscs = [];
var servicetranscs = [];
var bankname;
for (var i in Result) {
merchantname.push(Result[i].merchant_name);
successtranscs.push(Result[i].success_transcs);
failedtranscs.push(Result[i].failed_transcs);
servicetranscs.push(Result[i].service_transcs);
bankname = Result[i].bankname;
}
StackedChart(bankname, merchantname, successtranscs, failedtranscs, servicetranscs);
merchantname = [];
successtranscs = [];
failedtranscs = [];
servicetranscs = [];
if (counter == country.length - 1) {
counter = -1;
counter++;
}
else {
counter++;
}
},
error: function (Result) {
console.log(Result.d);
}
});
}
initfunc();
function callfunc() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/dashboard",
data: JSON.stringify({country: country[counter], bankid: bankid[counter]}),
dataType: "json",
success: function (Result) {
Result = Result.d;
console.log("result" +Result);
var data = [];
var merchantname = [];
var successtranscs = [];
var failedtranscs = [];
var servicetranscs = [];
var bankname;
for (var i in Result) {
merchantname.push(Result[i].merchant_name);
successtranscs.push(Result[i].success_transcs);
failedtranscs.push(Result[i].failed_transcs);
servicetranscs.push(Result[i].service_transcs);
bankname = Result[i].bankname;
}
StackedChart(bankname, merchantname, successtranscs, failedtranscs, servicetranscs);
merchantname = [];
successtranscs = [];
failedtranscs = [];
servicetranscs = [];
if (counter == country.length - 1) {
counter = -1;
counter++;
}
else {
counter++;
}
},
error: function (Result) {
console.log(Result.d);//it keeps going to the error //function
}
});
}
function StackedChart(bank_name,merch_name, succ_val, fail_val, ser_val) {
var myChart = Highcharts.chart('container1', {
chart: {
type: 'column'
},
title: {
text: bank_name
},
xAxis: {
categories: merch_name
},
yAxis: {
min: 0,
title: {
text: 'TransactionStatus'
},
stackLabels: {
enabled: true,
style: {
fontWeight: 'bold',
color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
}
}
},
legend: {
align: 'right',
x: -30,
verticalAlign: 'top',
y: 25,
floating: true,
backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || 'white',
borderColor: '#CCC',
borderWidth: 1,
shadow: false
},
tooltip: {
headerFormat: '<b>{point.x}</b><br/>',
pointFormat: '{series.name}: {point.y}<br/>Total: {point.stackTotal}'
},
plotOptions: {
column: {
stacking: 'normal',
dataLabels: {
enabled: true,
color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white'
}
}
},
series: [{
name: 'Servicefailure',
data: ser_val
}, {
name: 'Failure',
data: fail_val
}, {
name: 'Success',
data: succ_val
}]
});
}
setInterval(callfunc, 2000);
});
</script>
</body>
</html>
server.js -
var express = require('express');
var cnn = require('./DbConnection.js');
var bodyParser = require('body-parser');
require('highcharts');
var app = express();
app.use(express.bodyParser());
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); //
app.engine('html', require('ejs').renderFile);
dirname = "C:/Users/user/WebstormProjects/untitled/public";
require("jsdom").env("", function(err, window) {
if (err) {
console.error(err);
return;
}
var $ = require("jquery")(window);
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
});
app.get('/', function (req, res) {
var obj;
cnn.TransactionInfo("KENYA","57", function (err, result) {
// process result here
console.log(result.length);
var resultset = {"Result":result};
obj = { "title":"fruit consumption", "name":"fruit eaten"};
res.render("plain.ejs",{Resultset:resultset});
});
});
app.post('/dashboard', function (req, res) {
cnn.TransactionInfo(req.body.country,req.body.bankid, function (err, result) {
var resultset = {"Result":result};
res.render("plain.ejs",{Resultset:resultset});
});
});
By specifying dataType : "json", you're telling jQuery that it should expect JSON data to be returned by the server. However, your Express handler is sending back HTML:
res.render("plain.ejs",{Resultset:resultset});
So the error will likely be that jQuery couldn't decode the response.
Try sending back a JSON response:
res.json({ Resultset : resultset });
Related
I have a project where I created the backend with flask. It reads the data from the csv file and transfers it to html. It reads data every second with Ajax. Then I visualize the data with plotly.js. With Ajax, every get operation comes with a delay.I am working with approximately 2000 data.
However, there is a delay in my code. How can I refactor this code? What can I do to avoid delay?
$(function requestData() {
$.ajax({
type: "GET",
url: "/deneme3",
success: function (data) {
//console.log('success',data);
//console.log('success',data[0]);
//console.log('success',data[1]);
var enlem = [];
var boylam = [];
var ch1 = [];
var ch2 = [];
var ch3 = [];
var ch4 = [];
enlem = data[0];
boylam = data[1];
ch1 = data[2];
ch2 = data[3];
ch3 = data[4];
ch4 = data[5];
//console.log('enlem',enlem);
//console.log('boylam',boylam);
var trace1 = {
x: enlem,
y: boylam,
mode: "markers",
marker: {
size: 10,
color: ch1,
colorbar: { x: -0.2, len: 1 },
colorscale: "Jet",
},
};
var data = [trace1];
var layout = {
title: "Scatter Plot with a Color Dimension",
};
Plotly.newPlot("tester", data, layout);
setInterval(function () {
var update = {
x: [[enlem]],
y: [[boylam]],
};
Plotly.extendTraces("tester", update, [0]);
}, 100);
//ch1 grafik
var trace2 = {
y: ch1,
type: "scatter",
};
var data2 = [trace2];
var layout2 = {
title: "CH1",
};
Plotly.newPlot("ch1", data2, layout2);
setInterval(function () {
var update = {
y: [[ch1]],
};
Plotly.extendTraces("ch1", update, [0]);
}, 100);
//ch2 grafik
var trace3 = {
y: ch2,
type: "scatter",
};
var data3 = [trace3];
var layout3 = {
title: "CH2",
};
Plotly.newPlot("ch2", data3, layout3);
setInterval(function () {
var update = {
y: [[ch2]],
};
Plotly.extendTraces("ch2", update, [0]);
}, 100);
//ch3 grafik
var trace4 = {
y: ch3,
type: "scatter",
};
var data4 = [trace4];
var layout4 = {
title: "CH3",
};
Plotly.newPlot("ch3", data4, layout4);
setInterval(function () {
var update = {
y: [[ch3]],
};
Plotly.extendTraces("ch3", update, [0]);
}, 100);
//ch4 grafik
var trace5 = {
y: ch4,
type: "scatter",
};
var data5 = [trace5];
var layout5 = {
title: "CH4",
};
Plotly.newPlot("ch4", data5, layout5);
setInterval(function () {
var update = {
y: [[ch4]],
};
Plotly.extendTraces("ch4", update, [0]);
}, 100);
},
});
setTimeout(requestData, 100);
});
Also, which of the Ajax and socketio would it make more sense to use?
As discussed in the comments, something like this might work: initialize empty plots, then just fill in data in the update function:
function plotData(data) {
const [enlem, boylam, ...chs] = data;
Plotly.extendTraces("tester", {
x: [[enlem]],
y: [[boylam]],
}, [0]);
for (let i = 0; i < 4; i++) {
const j = i + 1;
Plotly.extendTraces(`ch${j}`, {
y: [[chs[i]]],
}, [0]);
}
// After success, wait before loading more data
setTimeout(requestData, 1000);
}
function requestData() {
// Simulate a successful response that returns 6 numbers.
plotData([Math.random(), Math.random(), Math.random(), Math.random(), Math.random(), Math.random()]);
// If a real endpoint was available, you could do something like
/*$.ajax({
type: "GET",
url: "/deneme3",
success: plotData,
});*/
}
function initialize() {
Plotly.newPlot("tester", [{
x: [],
y: [],
mode: "markers",
marker: {
size: 10,
colorbar: { x: -0.2, len: 1 },
colorscale: "Jet",
},
}], {
title: "Scatter Plot with a Color Dimension",
});
for (let i = 1; i <= 4; i++) {
Plotly.newPlot(`ch${i}`, [{
y: [],
type: "scatter",
}], {
title: `CH${i}`,
});
}
requestData(); // Fire off first update
}
$(initialize);
div {
width: 33%;
float: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.plot.ly/plotly-latest.min.js" charset="utf-8"></script>
<div id="tester"></div>
<div id="ch1"></div>
<div id="ch2"></div>
<div id="ch3"></div>
<div id="ch4"></div>
I currently have one js file that serves all the html scripts, that is starting to become tedious.
It looks like this:
// Using .html in jQuery big NO NO: https://medium.com/#jenlindner22/the-risk-of-innerhtml-3981253fe217, switched to .text
// Chart Variables
var teamProgressChart
// Get initial value from filters in /table
var seasonSelection = $('#seasonToggle').children(":first").val()
var typeSelection = $('#homeAwayToggle').children(":first").val()
var MatchweekSelection = $('#homeAwayToggle').children(":first").val()
// var leagueTableUpdateTimeStamp = 0
/**
* Team progress chart update in /table
*/
$(".clickable-row").click(function() {
const teamVal = $(this).attr('value')
$.ajax({
type: 'POST',
url: '/table/team?' + $.param({ teamId: teamVal }),
success: (res) => {
var result = res[0]
var points = result.pointsAll
var position = result.positionAll
var labels = result.gameweeks
console.log(points)
console.log(position)
console.log(labels)
if (teamProgressChart) {
teamProgressChart.data.labels = labels
teamProgressChart.data.datasets[0].data = points
teamProgressChart.data.datasets[1].data = position
teamProgressChart.update()
} else {
var ctx = document.getElementById('team-progress-graph').getContext('2d');
Chart.defaults.global.defaultFontSize = 24;
teamProgressChart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: [
{
label: "Points",
fillColor: "rgba(0,0,0,0)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(200,122,20,1)",
borderColor: "rgba(43, 87, 29, 0.9)",
fill: false,
data: points,
yAxisID: 'points'
},
{
label: "Position",
fillColor: "rgba(172, 26, 26, 0.9)",
strokeColor: "rgba(172, 26, 26, 0.9)",
pointColor: "rgba(172, 26, 26, 0.9)",
borderColor: "rgba(14, 86, 168, 0.9)",
fill: false,
data: position,
yAxisID: 'position'
},
],
},
options: {
scales: {
xAxes: [
{
ticks: {
fontSize: 24,
autoSkip: false,
beginAtZero: true
}
}
],
yAxes: [
{
id: 'points',
min: 0,
position: 'left',
ticks: {
fontSize: 24,
beginAtZero: true
}
},
{
id: 'position',
suggestedMin : 0,
suggestedMax : 20,
position: 'right',
ticks: {
fontSize: 24
}
},
]
},
display: false,
},
})
}
}
})
})
/**
* Button to updata data in /table
*/
$('#updateDataButton').bind('click', function(event){
console.log(event.timeStamp)
$.ajax({
type: 'POST',
url: '/table',
success: () => {
console.log('success')
window.location = "/";
}
})
});
/**
* Click eventlistner for home-page player stats
*/
const homeTable = document.querySelectorAll(".stats-item");
homeTable.forEach(element => {
element.addEventListener('click', homeTableToggle)
})
function homeTableToggle(event){
var queryVal = event.target.value
console.log(queryVal)
if (queryVal == 1){
$.ajax({
type: 'POST',
url: '/?' + $.param({ statsType: queryVal}),
success: (newVals) => {
$('#stats-placehld').text("AvgPlayTime")
$('#stats-placehld1').text("AvgPasses")
console.log($('#stats-placehld1').textContent)
$('#playerStatsAvg').empty();
for(let i = 0; i < 50; i++) {
let filteredTr = newVals[i]
let newHtml = `<tr>
<td>${filteredTr.name}</td>
<td>${filteredTr.teamName}</td>
<td>${filteredTr.position}</td>
<td>${filteredTr.averagePlaytime}</td>
<td>${filteredTr.averagePasses}</td>
</tr>`
$('#playerStatsAvg').append(newHtml)
}
}
})
} else if (queryVal == 2){
$.ajax({
type: 'POST',
url: '/?' + $.param({ statsType: queryVal}),
success: (newVals) => {
$('#stats-placehld').text("AvgShots")
$('#stats-placehld1').text("AvgOnTarget")
$('#playerStatsAvg').empty();
for(let i = 0; i < 50; i++) {
let filteredTr = newVals[i]
let newHtml = `<tr>
<td>${filteredTr.name}</td>
<td>${filteredTr.teamName}</td>
<td>${filteredTr.position}</td>
<td>${filteredTr.averageShotsPerGame}</td>
<td>${filteredTr.averageShotsOnTarget}</td>
</tr>`
$('#playerStatsAvg').append(newHtml)
}
}
})
}
}
//Click eventlistner for all table-filters
const selection = document.querySelectorAll(".dropdown-item");
selection.forEach(element => {
element.addEventListener('click', pickSelection)
})
function pickSelection(event) {
let text = ""
switch(event.target.parentElement.id){
case 'seasonToggle':
text = event.target.textContent
$('#seasonvalue').text(text)
seasonSelection = event.target.value
break
case 'homeAwayToggle':
text = event.target.textContent
$('#typevalue').text(text)
typeSelection = event.target.value
break
case 'matchWeekToggle':
text = event.target.textContent
$('#matchDropDownMenyButton').text(text)
MatchweekSelection = event.target.value
break
}
//Get request for
$.ajax({
type: 'POST',
url: '/table?' + $.param({ seasonVal: seasonSelection,
typeVal: typeSelection,
matchWeekVal: MatchweekSelection}),
success: (filteredSeasonValues) => {
$('#league-table-rows').empty();
for(let i = 0; i < 20; i++) {
let filteredTr = filteredSeasonValues[i]
let newHtml = `<tr>
<td>${i+1}</td>
<td><img src='badges/${filteredTr.team_shortName}.png' />
${filteredTr.team_shortName}</td>
<td>${filteredTr.played}</td>
<td>${filteredTr.won}</td>
<td>${filteredTr.drawn}</td>
<td>${filteredTr.lost}</td>
<td>${filteredTr.goalsFor}</td>
<td>${filteredTr.goalsAgainst}</td>
<td>${filteredTr.goalsDifference}</td>
<td>${filteredTr.points}</td>
</tr>`
$('#league-table-rows').append(newHtml)
}
}
})
}
How would one go about splitting it into multiple files, let's say page specific and importing them to a global js-file that later gets served, so the structure looks like this?
home.js
//home specific jquery functions
table.js
//table specific jquery functions
client.js
import home.js
import table.js
index.html
<script src="js/client.js" defer ></script>
I have an array of data of the following format:
[["sno","day","status","data1","data2","data3","data4"],
["1","01-12-2020","success","23","66","53","34"],
["2","02-12-2020","success","12","9","8","6"],
["3","03-12-2020","success","10","11","16","13"],
["4","04-12-2020","success","34","43","54","34"],
["5","01-12-2020","fail","45","26","36","44"],
["6","02-12-2020","fail","12","15","11","13"],
["7","03-12-2020","fail","34","43","33","29"],
["8","04-12-2020","fail","23","34","31","23"]
]
to display the particular text in Highcharts I used the Following code:
var weekData = [["sno","day","status","data1","data2","data3","data4"],["1","01-12-2020","success","23","66","53","34"],["2","02-12-2020","success","12","9","8","6"],["3","03-12-2020","success","10","11","16","13"],["4","04-12-2020","success","34","43","54","34"],["5","01-12-2020","fail","45","26","36","44"],["6","02-12-2020","fail","12","15","11","13"],["7","03-12-2020","fail","34","43","33","29"],["8","04-12-2020","fail","23","34","31","23"]] ;
//console.log(weekData);
function change()
{
var valStatus = document.getElementById("statusSelect");
status = valStatus.value;
//console.log(status);
if(status == 'success')
{
const successValues = weekData.filter((x)=>x[2] === "success"); //New Cases
console.log(successValues);
return successValues;
}
else if(status == 'fail')
{
const failValues = weekData.filter((x)=>x[2] === "fail"); //New Cases
console.log(failValues)
return failValues;
}
}
function getCol(matrix, col){
var column = [];
for(var i=0; i<matrix.length; i++){
column.push(matrix[i][col]);
}
return column;
}
function chartCreate()
{
change();
const toNumbers = arr => arr.map(Number);
var getstat= change();
var day = getCol(getstat,1);
console.log(day);
var sdata1 = toNumbers(getCol(getstat,3));
console.log("data 1" ,sdata1);
var sdata2 = toNumbers(getCol(getstat,4));
console.log(sdata2);
var sdata3 = toNumbers(getCol(getstat,5));
console.log(sdata3);
var sdata4 = toNumbers(getCol(getstat,6));
console.log(sdata4);
For the full program You can check my fiddle : https://jsfiddle.net/abnitchauhan/L27n0wfs/
the problem is that when I am status select box, The Chart is not updating.
Also I feel that this code is quite lengthy when the datasets will increase overtime. is there any efficient approach to display this data on Highchart's based on the same select options.
I made an update to JS code. See if this is what you want:
var weekData = [["sno","day","status","data1","data2","data3","data4"],["1","01-12-2020","success","23","66","53","34"],["2","02-12-2020","success","12","9","8","6"],["3","03-12-2020","success","10","11","16","13"],["4","04-12-2020","success","34","43","54","34"],["5","01-12-2020","fail","45","26","36","44"],["6","02-12-2020","fail","12","15","11","13"],["7","03-12-2020","fail","34","43","33","29"],["8","04-12-2020","fail","23","34","31","23"]] ;
//console.log(weekData);
function change()
{
var valStatus = document.getElementById("statusSelect");
status = valStatus.value;
//console.log(status);
if(status == 'success')
{
const successValues = weekData.filter((x)=>x[2] === "success"); //New Cases
console.log(successValues);
return chartCreate(successValues);
}
else if(status == 'fail')
{
const failValues = weekData.filter((x)=>x[2] === "fail"); //New Cases
console.log(failValues)
return chartCreate(failValues);
}
}
function getCol(matrix, col){
var column = [];
for(var i=0; i<matrix.length; i++){
column.push(matrix[i][col]);
}
return column;
}
function chartCreate(stat)
{
const toNumbers = arr => arr.map(Number);
var getstat= stat;
var day = getCol(getstat,1);
console.log(day);
var sdata1 = toNumbers(getCol(getstat,3));
console.log("data 1" ,sdata1);
var sdata2 = toNumbers(getCol(getstat,4));
console.log(sdata2);
var sdata3 = toNumbers(getCol(getstat,5));
console.log(sdata3);
var sdata4 = toNumbers(getCol(getstat,6));
console.log(sdata4);
var options = {
chart:{
renderTo: 'chart',
defaultSeriesType: 'line'
},
title: {
text: 'dummy'
},
subtitle: {
text: ' '
},
yAxis: {
title: {
text: ' ',
//tickPointInterval: 250
},
minorTickInterval: 'auto',
// tickInterval: 4,
},
xAxis: {
labels :{
minorTickInterval: 'auto',
formatter: function(){
return day[this.value];
}
},
tickInterval: 10
},
credits: {
enabled: false
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle'
},
plotOptions: {
series: {
label: {
connectorAllowed: false
},
// pointStart: 0
}
},
tooltip: {
// split: true,
formatter: function() {
var points = this.points,
tooltipArray = ['day: <b>' + day[this.x] + '</b><br/> Value : <b>'+ this.y +'</b>']
return tooltipArray;
}
},
series: [
{
name: 'Check',
data: sdata1
}],
responsive: {
rules: [{
condition: {
maxWidth: 500
},
chartOptions: {
legend: {
layout: 'horizontal',
align: 'center',
verticalAlign: 'bottom'
}
}
}]
}
};
var chart = new Highcharts.Chart(options);
$("#dataSelect").on('change', function(){
//alert('f')
var selVal = $("#dataSelect").val();
if(selVal == 'data1' || selVal == '')
{
options.series = [{name: 'Data', data: sdata1}];
options.yAxis = [{tickInterval:undefined, minorTickInterval: 'auto'}];
}
else if(selVal == 'data2')
{
options.series = [{name: 'Data', data: sdata2}]
}
else if(selVal == 'data3')
{
options.series = [{name: 'Data', data: sdata3}];
options.yAxis = [{tickInterval:undefined, minorTickInterval: 'auto'}];
}
else if(selVal == 'data4')
{
options.series = [{name: 'Data', data: sdata4}];
options.yAxis = [{tickInterval:undefined, minorTickInterval: 'auto'}];
}
var chart = new Highcharts.Chart(options);
});
}
change();
Your code looks very complex and does not fully work. In this case, I will suggest using the series setData method mixed with the change event listener. My example is a bit simplified, but I think it might be the right way.
document.getElementById('dataSelect').addEventListener('change', () => {
const selectorValue = document.getElementById('dataSelect').value
chart.series[0].setData(data[selectorValue])
});
API: https://api.highcharts.com/class-reference/Highcharts.Series#setData
Demo: https://jsfiddle.net/BlackLabel/nfz0a9bm/
I am trying to parse data from a JS Object array and get the value by passing field names and then saving the data in an array. But for some reason, I am not getting the right results. This is what I tried so far. I tried logging the results that I get in val and this is what I get.
val:Array[6]
0
:
Object
BankName
:
"IM BANK"
MERCHANTNAME
:
"MPesa"
NO_OF_FAILED_BANK_TRANSACTIONS
:
0
NO_OF_FAILED_SERVICE_TRANSACTIONS
:
2
NO_OF_SUCCESSFUL_TRANSACTIONS
:
28
__proto__
:
Object
1
:
Object
2
:
Object
3
:
Object
4
:
Object
5
:
Object
length
:
6
How Do I parse the data from my val array by passing field names and then store inside my merchantname array etc.
Homepage.js
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.3.min.js" ></script>
<script src="http://code.highcharts.com/highcharts.js" ></script>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>
<div id="container1" style="width:100%; height:400px;"></div>
<div id ="container2" style="height:20px;"></div>
<div id ="container3" style="width:100%; height:400px;"></div>
<script type="text/javascript">
$(document).ready(function () {
var bankid = [ 57, 9912, 9905, 16, 58 ];
var country = ["KENYA", "KENYA", "KENYA", "UGANDA", "UGANDA"];
var counter = 0;
var merchantname = [];
var successtranscs = [];
var failedtranscs = [];
var servicetranscs = [];
var bankname;
var rows =<%-JSON.stringify(Resultset)%>
function initfunc() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/dashboard",
data: JSON.stringify({country: country[counter], bankid: bankid[counter]}),
dataType: "json",
success: function (Result) {
Result = Result.Resultset
// console.log("result", Result);
// console.log("result",Result);
var data = [];
var merchantname = [];
var successtranscs = [];
var failedtranscs = [];
var servicetranscs = [];
var bankname;
$.each(Result, function(item, value){
console.log("val",value);
for (var i in value) {
$.each(value[i], function(item, val){
console.log(val);
for(var i =0;i<val.length;i++)
{
merchantname.push(val[i].merchant_name);
successtranscs.push(val[i].success_transcs);
failedtranscs.push(val[i].failed_transcs);
servicetranscs.push(val[i].service_transcs);
bankname =val[i].bankname;
console.log("merchantname",merchantname);
}
//
})
}
})
// merchantname.push(Result[i].merchant_name);
// successtranscs.push(Result[i].success_transcs);
// failedtranscs.push(Result[i].failed_transcs);
// servicetranscs.push(Result[i].service_transcs);
// bankname = Result[i].bankname;
// console.log("merchantname",merchantname);
StackedChart(bankname, merchantname, successtranscs, failedtranscs, servicetranscs);
merchantname = [];
successtranscs = [];
failedtranscs = [];
servicetranscs = [];
if (counter == country.length - 1) {
counter = -1;
counter++;
}
else {
counter++;
}
},
error: function (Result) {
console.log(Result);
}
});
}
initfunc();
function StackedChart(bank_name,merch_name, succ_val, fail_val, ser_val) {
var myChart = Highcharts.chart('container1', {
chart: {
type: 'column'
},
title: {
text: bank_name
},
xAxis: {
categories: merch_name
},
yAxis: {
min: 0,
title: {
text: 'TransactionStatus'
},
stackLabels: {
enabled: true,
style: {
fontWeight: 'bold',
color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
}
}
},
legend: {
align: 'right',
x: -30,
verticalAlign: 'top',
y: 25,
floating: true,
backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || 'white',
borderColor: '#CCC',
borderWidth: 1,
shadow: false
},
tooltip: {
headerFormat: '<b>{point.x}</b><br/>',
pointFormat: '{series.name}: {point.y}<br/>Total: {point.stackTotal}'
},
plotOptions: {
column: {
stacking: 'normal',
dataLabels: {
enabled: true,
color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white'
}
}
},
series: [{
name: 'Servicefailure',
data: ser_val
}, {
name: 'Failure',
data: fail_val
}, {
name: 'Success',
data: succ_val
}]
});
}
setInterval(initfunc, 2000);
});
</script>
</body>
</html>
Your access keys (marchant_name, success_transcs, ..) are not same with the keys of the objects in the array (MERCHANTNAME, NO_OF_FAILED_BANK_TRANSACTIONS, ...).
Try using the exact same keys:
...
merchantname.push(val[i].MERCHANTNAME);
successtranscs.push(val[i].NO_OF_SUCCESSFUL_TRANSACTIONS);
...
Nested loops in initfunc() look all wrong.
Callback signature
$.each()'s callback signature is (item, index)
Nesting
Do you realise that $.each(function() {...}) is a looping structure in its own right, without the need of a for loop?
You have loops nested at 4-levels. In summary :
$.each(..., { // outer loop (n1 iterations)
for(...) { // first inner loop (n2 iterations)
$.each(..., function(element2, index2) { // second inner loop (n3 iterations)
for() { // third inner loop (n4 iterations)
// Here, inner statements are called n1 x n2 x n3 x n4 times
}
});
}
});
That's not necessarily wrong, but it's very unusual to need loops nested that deeply.
I rather imagine you want :
$.each(Result, function(item) {
$.each(item, function(val) {
merchantname.push(val.merchant_name); // or .MERCHANTNAME?
successtranscs.push(val.success_transcs); // or .NO_OF_SUCCESSFUL_TRANSACTIONS?
failedtranscs.push(val.failed_transcs); // or .NO_OF_FAILED_BANK_TRANSACTIONS?
servicetranscs.push(val.service_transcs); // or .NO_OF_FAILED_SERVICE_TRANSACTIONS?
bankname = val.bankname; // or .BankName?
});
});
or maybe just :
$.each(Result, function(val) {
merchantname.push(val.merchant_name); // or .MERCHANTNAME?
successtranscs.push(val.success_transcs); // or .NO_OF_SUCCESSFUL_TRANSACTIONS?
failedtranscs.push(val.failed_transcs); // or .NO_OF_FAILED_BANK_TRANSACTIONS?
servicetranscs.push(val.service_transcs); // or .NO_OF_FAILED_SERVICE_TRANSACTIONS?
bankname = val.bankname; // or .BankName?
});
I have the following HTTP request that i use to fill out my chart:
$scope.series = ['Moduler tager', 'Gns.score'];
$scope.activity_data = [];
$scope.activity_ticks = [];
var tmp_data = [];
$scope.bar = [];
$scope.line = [];
$http.get(api.getUrl('findSelfActivityByDivisions', null))
.success(function (response) {
response.forEach(function(y){
var i = 0;
var log_date = y.date.substr(0, y.date.indexOf('T'));
var date = new Date(log_date);
var logg_date = moment(date).fromNow();
var indexOf = tmp_data.indexOf(logg_date);
var found = false;
var index = 0;
if(tmp_data.length > 0){
tmp_data.forEach(function(current_data){
if(current_data[0] == logg_date){
found = true;
}
if(!found){
index++;
}
})
}
if(found){
var tmp = tmp_data[index];
tmp[1] = tmp[1] + y.num_modules;
tmp[2] = tmp[2] + y.num_score_modules;
tmp[3] = tmp[3] + y.sum_score;
tmp_data[index] = tmp;
}
else
{
var tmp = [logg_date, y.num_modules, y.num_score_modules, y.sum_score];
tmp_data.push(tmp);
}
})
var line = [];
var bar = [];
tmp_data.forEach(function(data){
$scope.activity_ticks.push(data[0])
line.push(data[1]);
var avg_score = data[3] / data[2];
if(isNaN(avg_score)){
avg_score = 0;
}
bar.push(avg_score);
});
$scope.line = line;
$scope.bar = bar;
});
Now then i have the following chart config:
$scope.chartConfig = {
options: {
chart: {
type: 'areaspline'
}
},
series: [{
data: $scope.bar,
type: 'column'
},{
data: $scope.line,
type: 'line'
}],
xAxis: {
categories: $scope.activity_ticks
},
title: {
text: 'Hello'
},
loading: false
}
Sadly none of the graphs are showing (im guessing it has something to do with the date comming after the load)
Can anyone help me out?
Your $scope.chartConfig is likely firing before the success callback of your $http.get(api.getUrl('findSelfActivityByDivisions', null)) completes. I am assuming $scope.chartConfig is located in a controller. Try placing a $watchGroup on the values then apply your chart rendering logic once those values resolve. An example may include
Note that $watchGroup is found within Angular as of 1.3
$scope.$watchGroup(['line', 'bar'], function(newValues, oldValues) {
// newValues[0] --> $scope.line
// newValues[1] --> $scope.bar
if(newValues !== oldValues) {
$scope.chartConfig = {
options: {
chart: {
type: 'areaspline'
}
},
series: [{
data: $scope.bar,
type: 'column'
},{
data: $scope.line,
type: 'line'
}],
xAxis: {
categories: $scope.activity_ticks
},
title: {
text: 'Hello'
},
loading: false
}
}
});