values not updated after an ajax response - javascript

I am sending some form data via ajax to a php script in the same page. PHP must process the data and show results in the same page.
I am using this syntax for ajax:
$.ajax
({
type: "POST",
url: "",
data: $("form").serialize(),
success: function(result)
{
updatechart();
console.log(result);
}
});
I am basically trying to update some values in a chart based on data entered in the form and after processed by a php script. I get the whole source of the page when I do console.log(result); and the values are updated in my console after doing this but the chart is not updated. When I view-source the page, the values remain the same. What should I do?
function updatechart() {
var json=<?php echo json_encode($GLOBALS['json']); ?>;
var direct=json['direct'];
var total=json['total'];
var referred=total-direct;
var aid=new Array();
var count=new Array();
for(var i=0;i<json['aid'].length;i++) {
aid[i]=json['aid'][i];
count[i]=json['count'][i];
}
var series = [{
name : "Referred",
data: [referred]
}, {
name: "Direct",
data: [direct]
}];
for(var i=0; i<aid.length;i++) {
series.push({
name: 'AID-'+[aid[i]],
data: [count[i]]
})
}
var options = {
chart: {
renderTo: 'container',
type: 'column'
},
title: {
text: 'User Source Chart'
},
xAxis: {
categories: ['Users']
},
yAxis: {
min: 0,
title: {
text: 'Total users'
}
},
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.percentage:.0f}%)<br/>',
shared: true
},
plotOptions: {
column: {
stacking: 'percent'
}
},
series: series
};
chart = new Highcharts.Chart(options);
}
This is my updatechart() code. The problem is, json value is not updated.

Pass the result as parameter to updatechart()
$.ajax
({
type: "POST",
url: "",
data: $("form").serialize(),
success: function(result)
{
updatechart(result);
}
});
then access the results via parameter.
function updatechart(result) {
//.......
//.......
console.log(result);
}
Hope you're trying something like this.

That is expected behavior. Move your PHP processing to a different page.
$.ajax
({
type: "POST",
url: "anotherphppage.php",
data: $("form").serialize(),
success: function(result)
{
updatechart(result);
}
});
Try this and you'll see what I mean:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#mybutt').click(function() {
$.ajax({
type: "POST",
url: "",
data: 'myVar=Hello',
success: function(data) {
alert(data);
}
});
});
}); //END $(document).ready()
</script>
</head>
<body>
Try this:<br />
<input type="button" id="mybutt" value="Click Me">
</body>
</html>

Related

Apexcharts remove old data series before render new series

I'm using apex chart for simple data visualization from json output. My charts based on pure javascript and not Vue or other frameworks.
My json (php) backend create two json outputs fro draw the chart as below
JSON 1
{
"x": "2019-05-27 16:18:48",
"y": "100"
},
{
"x": "2019-05-27 16:25:09",
"y": "110"
},
JSON 2
{
"x": "2019-05-27 16:18:48",
"y": "60"
},
{
"x": "2019-05-27 16:25:09",
"y": "65"
},
Based on the above two json outputs I retrieve data and draw my graph using the Category paired values method. below is the code responsible for retrieve data and draw the chart.
function for getting json data
function data_function(){
$.ajax({
type: "Get",
url: backend,
data:{
param: "all_a"
},
async: true,
cache: false,
success: function(data) {
a_data = data;
$.ajax({
apex_task: "Get",
url: backend,
data:{
param: "all_b"
},
async: true,
cache: false,
success: function(data) {
b_data = data;
chart(a_data,b_data);
}
});
}
});
}
function for draw chart
function draw_chart(a_data,b_data) {
var options = {
chart: {
height: 400,
type: 'bar',
stacked: false
},
series: [
{
name: 'a',
data: a_data,
},
{
name: 'b',
data: b_data,
}],
yaxis: [
{
axisTicks: {
show: true,
},
axisBorder: {
show: true,
color: '#008FFB'
},
labels: {
style: {
color: '#008FFB',
}
}
},
]
}
var chart = new ApexCharts(document.querySelector("#chartdiv"), options);
chart.render();
}
This works fine until I second time render the chart with new data. when I load the different data without reloading the windows chart happen to be laggy and render multiple times with the old incorrect data. sometimes I have to run the data_fnction multiple times to render the chart properly.
How can I fix this? Do I need to use function like appendchart ? how can I use wiht my data_function
You should call the render() method just once in the beginning (even with empty array it should work), then call the updateSeries() method in ajax call to update data of the chart.
var options = {
chart: {
height: 400,
type: 'bar',
stacked: false
},
series: [],
yaxis: [{
axisTicks: {
show: true,
},
axisBorder: {
show: true,
color: '#008FFB'
},
labels: {
style: {
color: '#008FFB',
}
}
}]
}
var chart = new ApexCharts(document.querySelector("#chartdiv"), options);
chart.render();
Your ajax call with updateSeries method of the chart
function data_function() {
$.ajax({
type: "Get",
url: backend,
data: {
param: "all_a"
},
async: true,
cache: false,
success: function (data) {
a_data = data;
$.ajax({
apex_task: "Get",
url: backend,
data: {
param: "all_b"
},
async: true,
cache: false,
success: function (data) {
b_data = data;
chart.updateSeries([{
name: 'a',
data: a_data
}, {
name: 'b',
data: b_data
}])
}
});
}
});
}
Docs for updateSeries
Although there is the updateSeries function, you're allowed to render again the values of the chart by destroying the previous ones. This works with ApexCharts, ChartJS, etc.
var options =
{
series: [],
chart:
{
type: 'donut',
height: 150
},
labels: ['...'],
};
// Destroy if exists in order to re-update the data
if (window.myChart)
window.myChart.destroy();
window.myChart = new ApexCharts(chart, options);
window.myChart.render();

C3 chart with JSON data

I am trying to populate a C3 chart with dynamic data from a SQL database. I have c# web method that when called by my javascript produces the following JSON string
[{"y":"5","item1":"Lion Wharf"},{"y":"31","item1":"Millbrook Park P2"},{"y":"84","item1":"Pinfield Meadows"}]
I'm using the following javascript on pageload but getting error "a.forEach is not a function"
$.ajax({
type: "POST",
url: "additions.aspx/GetPiechartData",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: "true",
cache: "false",
success: function (result) {
OnSuccess(result.d);
},
error: function (xhr, status, error) {
alert(error);
}
});
function OnSuccess(response) {
var abc = JSON.stringify(response);
window.location.replace(response);
var chart = c3.generate({
bindto: '#chart-var-project',
data: {
json: response,
keys: {
x: 'y',
value: ['item1']
},
type: 'donut'
},
donut: {
title: "Approval",
width: 40,
label: {
show: false
}
},
color: {
pattern: ["#ff9800", "#78c350", "#f7531f"]
}
});
I'm very new to Javascript and would really appreciate a pointer here
Thanks!
You have to format your json response to fit the expected format of C3 for Donut graph type.
function OnSuccess(response) {
var data = {};
var value = [];
JSON.parse(response).forEach(function(d) {
data[d.item1] = d.y;
value.push(d.item1);
});
c3.generate({
data: {
json: [data],
keys: {
value : value
},
type: 'donut'
},
donut: {
title: "Approval",
width: 40,
label: {
show: false
}
},
color: {
pattern: ["#ff9800", "#78c350", "#f7531f"]
}
})
}
Your server will normally output a string, so using a JSON.parse will transform this string into a json object.
function OnSuccess(response) {
var jsonData = response.d;
var chart = c3.generate({
bindto: '#chart-var-project',
data: {
json: JSON.parse(jsonData),
}
});
}

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)
}]
});
}
});

display a linear highchart with data from database

i'm trying to display data from database into a linear highchart. this is the json response from my controller which is retrieved from database:
[{"protocole":"tcp","date":"01/02/20","time":"00:10:20","total":281},
{"protocole":"udp","date":"01/02/20","time":"00:10:30","total":201},
{"protocole":"tcp","date":"01/02/20","time":"00:10:40","total":100}}
i succeeded to display data in the yAxix from data base but i've tested it with static data in the xAxix this is the code :
$(document).ready(function() {
var options={
chart: {
renderTo: 'container',
type: 'line'
},
title : {
text: 'Total Request number'
},
subtitle : {
text: 'Server num1'
},
xAxis : {
categories: ['00:10:20','00:10:30','00:10:40']
},
yAxis :{
title: {
text: 'Total'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip : {
valueSuffix: '\xB0C'
},
legend : {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
borderWidth: 0
},
series : [{}]
}
$.ajax({
type: 'GET',
contentType : 'application/json',
dataType: 'JSON',
url: 'jsonsdp',
data: "",
success: function(data){
var array=[] ;
$.each(data, function(i) {
array.push(data[i].total);
})
alert(array);
options.series[0]= {"name": 'total',
"data":array};
var chart = new Highcharts.Chart(options);
}
});
});
now i want the categories to be dynamic and retrieve time and put it on axis .
I have tried this code but still not working !
$.ajax({
type: 'GET',
contentType : 'application/json',
dataType: 'JSON',
url: 'jsonsdp',
data: "",
success: function(data){
var array=[] ;
var array1=[];
$.each(data, function(i) {
array.push(data[i].total);
array1.push(data[i].time);
})
// alert(array);
options.series[0]= {"name": 'total',
"data":array};
options.xAxis.categories=array1;
var chart = new Highcharts.Chart(options);
}
});
do somebody have an idea how to do this ?
thanks in advance .
I've tested this code and it works perfectly !
I don't know why this didn't work for the first time and showed errors and now works !
I post it maybe it could help someOne. if someone knows why it will be better to mention it .
$.ajax({
type: 'GET',
contentType : 'application/json',
dataType: 'JSON',
url: 'jsonsdp',
data: "",
success: function(data){
var array=[] ;
var array1=[];
$.each(data, function(i) {
array.push(data[i].total);
array1.push(data[i].time);
})
// alert(array);
options.series[0]= {"name": 'total',
"data":array};
options.xAxis.categories=array1;
var chart = new Highcharts.Chart(options);
}
});

adding custom parameters for highcharts using ajax

I'm trying to add some parameters to my highcharts that are being called by ajax. I call all the necessary parameters in a separate php, then the success result would put it in the container for highcharts.
My Code:
$.ajax({
type: 'post',
url: 'sdayresult.php',
data: $("#FormName").serialize(),
success: function(data) {
//$("#anser").html(data);
$('#container').highcharts({data});
}
The value of the data:
chart: {
type: 'scatter'
},
title: {
text: 'Search by Airline'
},
xAxis: {
categories: ['none']
},
yAxis: {
title: {
text: '# of Crew'
}
},
series: [{
name: '# of Crew',
URLs: ['#'],
data: [0],
point: {
events: {
click: function() {
var someURL = this.series.userOptions.URLs[this.x]; // onclick get the x index and use it to find the URL
if (someURL)
window.open('http://'+someURL);
}}}
}]
But when I run the script, the is a javascript error saying that I have an undefined "}". I tried pasting the value of the data to another test page of highcharts and it seems that the value of data is correct. What should I do to fix it?

Categories

Resources