How to pass an jquery ajax response after success into a php variable. this is my code :
process.php
$start = "";
$end = "";
if(isset($_POST['tampStart']))
{
$start = $_POST['tampStart'];
}
if(isset($_POST['tampEnd']))
{
$end = $_POST['tampEnd'];
}
$SQL = "SELECT * FROM `values` WHERE date BETWEEN '".$start."' and '".$end."'";
$result = mysql_query($SQL);
$prefix = '';
while ( $row = mysql_fetch_assoc( $result ) ) {
$prefix .= "[\n"."'".$row['month']."'".', '.$row['days']."]".",";
}
echo rtrim($prefix, ",");
index.php
var dStart = $('#textInput1').val();
var dEnd = $('#textInput2').val();
var form_data = {
tampStart: dStart,
tampEnd: dEnd
};
$.ajax({
url: 'process.php',
type: 'POST',
async : true,
data: form_data,
dataType: 'text',
success: function(resp){
$('#content').html(resp);
//pass to php variable ?
}
});
there is no problem when I put the response into a div ($('#content').append(resp);), but how to put the response into an php variable. Thanks for advance..
update my Highcharts code :
function createChart(datan) {
//alert(datan);
Highcharts.setOptions({
lang: {
drillUpText: 'Back to {series.name}'
}
});
var options = {
chart: {
height: 300
},
title: {
text: 'Highcharts Drilldown Plugin'
},
xAxis: {
categories: true
},
drilldown: {
series: [{
id: 'fruits',
name: 'Fruits',
data: [datan] //here #*
}, {
id: 'cars',
name: 'Cars',
data: [{
name: 'Toyota',
y: 4,
drilldown: 'toyota'
},
['Volkswagen', 3],
['Opel', 5]
]
}, {
id: 'toyota',
name: 'Toyota',
data: [
['RAV4', 3],
['Corolla', 1],
['Carina', 4],
['Land Cruiser', 5]
]
}]
},
legend: {
enabled: false
},
plotOptions: {
series: {
dataLabels: {
enabled: true
},
shadow: false
},
pie: {
size: '80%'
}
},
series: [{
name: 'Overview',
colorByPoint: true,
data: [{
name: 'Fruits',
y: 10,
drilldown: 'fruits'
}, {
name: 'Cars',
y: 12,
drilldown: 'cars'
}, {
name: 'Countries',
y: 8
}]
}]
};
// Column chart
options.chart.renderTo = 'container1';
options.chart.type = 'column';
var chart1 = new Highcharts.Chart(options);
}
I make the highcharts config to a function. when I alert(datan), its shown the data from ajax response, but when I put on Drilldown option data (see sign #* above), the highchart config cant read it..
PHP runs on server not on client so the thing you asking is possible only on server. You have to customize this code for your need it gives framework.
$.ajax({
url: 'process.php',
type: 'POST',
async : true,
data: form_data,
dataType: 'text',
success: function(resp){
// $('#content').html(resp);
createChart(resp);
}
});
var chart;
function createChart(data) {
var options = {
chart: {
height: 300
},
title: {
text: 'Highcharts Drilldown Plugin'
},
xAxis: {
categories: true
},
drilldown: {
series: data}
};
options.chart.renderTo = 'content';
options.chart.type = 'column';
var chart1 = new Highcharts.Chart(options);
}
Javascript is a client side scripting. You can't assign the javascript value directly to the php variable.
One way is to set a SESSION variable in PHP. In your case in process.php file.
Another way is to use Database/files.
Well, if you really want to do it this way, you can set a cookie with the desired variable in Javascript and afterwards access it with PHP.
But, there is another way. You can do whatever you want on the client side and when you want to transmit the variable to server-side, just open an ajax connection on the php page which will handle the variable and hand it the actual variable through POST data.
Related
this is my first time posting here, so I apologize in advanced if I missed something I needed to include.
I am trying to create a donut chart with data from a php file, and even though the array loads and is visible in the console log, the following error is shown.
Failed to create chart: can't acquire context from the given item
<div id="trafficChart" style="min-height: 400px;" class="echart"></div>
<script>
var Name = [];
var Q_Sold = [];
$(document).ready(function(){
$.ajax({
url: "https://host-3:8890/data.php",
method: "GET",
success: function(data) {
console.log(data);
Name = [];
Q_Sold = [];
for(var i in data) {
Name.push(data[i].Name);
Q_Sold.push(data[i].Q_Sold);
}
},
error: function(data) {
console.log(data);
}
});
});
document.addEventListener("DOMContentLoaded", () => {
echarts.init(document.querySelector("#trafficChart")).setOption({
tooltip: {
trigger: 'item'
},
legend: {
top: '5%',
left: 'center'
},
series: [{
name: 'Access From',
type: 'pie',
radius: ['40%', '70%'],
avoidLabelOverlap: false,
label: {
show: false,
position: 'center'
},
emphasis: {
label: {
show: true,
fontSize: '18',
fontWeight: 'bold'
}
},
labelLine: {
show: false
},
data: [{
value: Q_Sold,
name: Name
}]
}],
});
});
</script>
</div>
</div>
However if I change the data values from
data: [{
value: Q_Sold,
name: Name
}]
To
data: [{
value: 1000,
name: "Name"
}]
The Chart renders perfectly fine. I have no clue to what the problem might be.
I'm trying to pass the string value from my controller to my javascript to render my chart thru on click of a button.
In my controller I query the needed data and echo the return value, below is the value
new CanvasJS.Chart("myChart", {
animationEnabled: true,
theme: "light2",
title:{
text: "Devices"
},
axisY: {
title: "From"
},
legend: {
cursor:"pointer",
itemclick : toggleDataSeries
},
toolTip: {
shared: true,
content: toolTipFormatter
},
data: [
{
type: "bar",
showInLegend: true,
name: "A",
dataPoints: [{ y: 2, label: "Keyboard" },{ y: 13, label: "Laptop" }]},{
type: "bar",
showInLegend: true,
name: "B",
dataPoints: [{ y: 1, label: "Keyboard" },{ y: 0, label: "Laptop" }]}
]
})
I used ajax to get the value above like below:
var return_first = function () {
var tmp = null;
$.ajax({
'async': false,
'type': "POST",
'global': false,
'dataType': 'html',
'url': base_url + 'my_controller/dChart',
'data': {
'dev_fil' : $("#dev_fil").val()
},
'success': function (data) {
tmp = data;
}
});
return tmp;
}();
And then I will assign it to a variable and render() it
var chart = return_first;
chart.render();
But it keeps on returning and error Uncaught TypeError: chart.render is not a function
I tried to just render it normally and not from ajax it displays the chart but I need to change the value of the chart when submitting a device name.
Thank you in advance for the help.
---UPDATE---
I tried to pass only the values inside the data[] and call the render() inside the success.
var return_first = function () {
var tmp = null;
$.ajax({
'async': false,
'type': "POST",
'global': false,
'dataType': "html",
'url': base_url + 'my_controller/dChart',
'data': {
'dev_fil' : $("#dev_fil").val()
},
'success': function (data) {
console.log(data)
tmp = new CanvasJS.Chart("myChart", {
animationEnabled: true,
theme: "light2",
title:{
text: "Device Replacement"
},
axisY: {
title: "Outlets"
},
legend: {
cursor:"pointer",
itemclick : toggleDataSeries
},
toolTip: {
shared: true,
content: toolTipFormatter
},
data: [data]
});
tmp.render();
}
});
return tmp;
}();
I'm having an error
Uncaught TypeError: Cannot use 'in' operator to search for 'name' in {
type: "bar",
showInLegend: true,
name: "AA",
dataPoints: [{ y: 13, label: "Laptop" }]}
Its at canvas.minjs
The data comes through as a string, so you are assigning tmp to a string, which does not have the function render(). You need to eval() the string to have it execute the string as code, which would then create your object:
'success': function (data) {
tmp = eval(data);
}
Just a note, eval is generally not the best way to do things. Here you might consider returning just the json settings in your API and creating the object in the success:
var return_first = function () {
var tmp = null;
$.ajax({
'async': false,
'type': "POST",
'global': false,
'dataType': 'json', // notice we changed to 'json' here
'url': base_url + 'my_controller/dChart',
'data': {
'dev_fil' : $("#dev_fil").val()
},
'success': function (data) {
tmp = new CanvasJS.Chart("myChart", data);
}
});
return tmp;
}();
--- UPDATE ---
Based on your most recent code, you want your server side to be returning this:
[
{
type: "bar",
showInLegend: true,
name: "A",
dataPoints: [{ y: 2, label: "Keyboard" },{ y: 13, label: "Laptop" }]},{
type: "bar",
showInLegend: true,
name: "B",
dataPoints: [{ y: 1, label: "Keyboard" },{ y: 0, label: "Laptop" }]}
]
and your client-side code will look like this:
var return_first = function () {
var tmp = null;
$.ajax({
'async': false,
'type': "POST",
'global': false,
'dataType': "json", // note we set json here
'url': base_url + 'my_controller/dChart',
'data': {
'dev_fil' : $("#dev_fil").val()
},
'success': function (data) {
console.log(data)
tmp = new CanvasJS.Chart("myChart", {
animationEnabled: true,
theme: "light2",
title:{
text: "Device Replacement"
},
axisY: {
title: "Outlets"
},
legend: {
cursor:"pointer",
itemclick : toggleDataSeries
},
toolTip: {
shared: true,
content: toolTipFormatter
},
data: data // notice data is not wrapped in brackets because it's already an array
});
tmp.render();
}
});
return tmp;
}();
var chart = return_first;
chart.render();
return_first is your function that is making an ajax call, and you are assigning that to chart. So its normal that javascript is saying: hey, your return_first function doesnt have a function called render.
Maybe you need to assign to another variable your ChartJS var, and then call from there the render. Something like:
var myChart = new CanvasJS.Chart(...);
myChart.render();
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();
I have this code in javascript for chart column:
$(function () {
$('#grafic_column').highcharts({
chart: {
type: 'column'
},
series: [{
name: 'Population',
data: [
['Shanghai', 23.7],
['Lagos', 16.1],
['Istanbul', 14.2]
]
}]
});
});
And this cod in php:
<?php
$ar = array(
['Shanghai', 23.7],
['Lagos', 16.1],
['Istanbul', 14.2]
);
echo json_encode($ar);
?>
How do import the values results from php in series.data:? Thank you!
Assuming your PHP file is accessible with a server, you can just perform $.get to make an AJAX request to the file serving the data:
$(function () {
$.get('/yourphpfile.php').then(function(data) {
$('#grafic_column').highcharts({
chart: {
type: 'column'
},
series: [{
name: 'Population',
data: data
}]
});
})
});
I have to create the following graph and i have to dynamically load data into it.
Basic Area http://domoticx.com/wp-content/uploads/highcharts-area-basic-standaard.png
Could anyone please help me understanding how can it be done.
Below is where i am able to reach.:
$.ajax({
url: 'EthicsData',
dataType: "json",
type: "GET",
contentType: 'application/json; charset=utf-8',
async: false,
processData: false,
cache: false,
delay: 150,
success: function (data) {
var EthicReg = (data[0].regdet);
var EthicComp = (data[0].compdet);
var EthicsCompletions = new Array();
var EthicsRegistration = new Array();
for (var i in EthicReg) {
var serie = new Array(EthicReg[i].Value, EthicReg[i].year);
EthicsRegistration.push(serie);
}
for (var y in EthicComp) {
var series2 = new Array(EthicComp[y].value,
EthicComp[y].year);
EthicsCompletions.push(series2);
}
DrawEthicsAndCompl(EthicsCompletions, EthicsRegistration)
},
error: function (xhr) {
alert('error');
}
});
};
function DrawEthicsAndCompl(EthicsCompletions, EthicsRegistration) {
debugger;
var chart = new Highcharts.Chart({
chart: {
//plotBackgroundColor: null,
//plotBorderWidth: 1, //null,
//plotShadow: false,
renderTo: 'container1',
type: 'area'
},
title: {
text: 'US and USSR nuclear stockpiles'
},
subtitle: {
text: 'something'
},
xAxis: {
allowDecimals: false,
labels: {
formatter: function () {
return 10; // clean, unformatted number for year
}
}
},
yAxis: {
title: {
text: 'Nuclear weapon states'
},
labels: {
formatter: function () {
return this.value;
}
}
},
tooltip: {
pointFormat: '{series.name} produced <b>{point.y:,.0f}</b><br/>warheads in {point.x}'
},
plotOptions: {
area: {
pointStart: 2010,
marker: {
enabled: false,
symbol: 'circle',
radius: 2,
states: {
hover: {
enabled: true
}
}
}
}
},
series: [{
name: 'Registration',
data: [EthicsRegistration[0]]
}, {
name: 'Completions',
data: [EthicsCompletions[0]]
}]
});
}
Here is the link which demo's same but static data:
(http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/area-basic/)
Just change the order in which you are pushing items in array , means
Instead
var serie = new Array(EthicReg[i].Value, EthicReg[i].year);
EthicsRegistration.push(serie);
Use
var serie = new Array(EthicReg[i].year, EthicReg[i].Value);
EthicsRegistration.push(serie);
Also , If you are getting year's value don't use pointStart: 2010 instead leave it on the data you are getting from the response above.
Thanks #Nishith for providing the right direction. I modified the code as below:
name: 'Registration',
data: [EthicsRegistration[0][1], EthicsRegistration[1][1], EthicsRegistration[2][1]]
}, {
name: 'Completions',
data: [EthicsCompletions[0][1],EthicsCompletions[1][1],EthicsCompletions[2][1]]
}]
});