<script>
$.getJSON('chartState',{
stateCode : $(this).val(),
ajax : 'true'
},
function(data) {
alert("state data"+data);
});
</script>
I have the value in data and want to show in javascript given below.
The fields data is given want to push my state data there.
<script>
var salesChartData = {
datasets: [{
data: ["here i want my data"]
}]
};
</script>
Both are written in diffrent script
datasets is an array with an object on index 0. So to define or redeclare the data property in there the syntax is
salesChartData.datasets[0].data = data;
Use it in your callback function:
function(data) {
salesChartData.datasets[0].data = data;
});
Not sure if I understand correctly, is this what you need?
var salesChartData = {
datasets: [
{
data : {}
}
]
};
$.getJSON('chartState',{
stateCode : $(this).val(),
ajax : 'true'
},
function(data) {
salesChartData.datasets[0].data = data;
});
Just set the data after receiving it
if you need to show the ajax result in a variable salesChartData, you can try this
salesChartData.datasets[0].data[0] = "new data"
salesChartData is a JSON object with key datasets contains an array of JSON objects.
So if salesChartData is declared globally, then you can replace in the success of the ajax
Here below, it done using web storage. This is used to access from different file.
// File 1
var salesChartData = {
datasets: [{
data: ["here i want my data"]
}]
};
localStorage.setItem("salesChart", JSON.stringify(salesChartData));
//-----------------------------------------------------------------------
// File 2
var salesChartData = JSON.parse(localStorage.getItem("salesChart"));
// ajax call
$.getJSON('chartState', {
stateCode: $(this).val(),
ajax: 'true'
},
function (data) {
alert("state data" + data);
salesChartData.datasets[0].data[0] = data // "new data"
});
Hope this will work.
Thank You
I have done with my self
$.getJSON('chartState',{
stateCode : $(this).val(),
ajax : 'true'
},
function(data) {
var chr=data;
var a=chr[0];var b=chr[1];var c=chr[2];var d=chr[3];
var e=chr[4];var f=chr[5];var g=chr[6];
After that I have sended one by one data
var salesChartData = {
datasets: [
{
data : [g,f,e,d,c,b,a]
}
]
};
As you mention that both parts of the script are in different tags you can solve the problem with a global, this is not recommended. The better solution would be to refactor the structure and not have multiple script tags. But if you have no control over this then you should do something like this:
<script>
// No var used to make it global
chart_state_data = false;
$.getJSON('chartState',{
stateCode : $(this).val(),
ajax : 'true'
},
function(data) {
// the data is set to this variable on callback
chart_state_data = data
});
</script>
And:
<script>
// chart_state_data contains data retrieved from ajax call or false
var salesChartData = {
datasets: [{
data: chart_state_data
}]
};
</script>
Related
I'm trying to display a chart in apexcharts, and use a variable as the data. When I do this, nothing is displayed. See the following:
var message = '[1,4]'
var options = {
chart: {
type: 'line',
sparkline: {
enabled: true,
}
},
series: [{
data: message,
}],
}
var chart = new ApexCharts(document.querySelector("#chart"), options);
chart.render();
Using the variable message as data doesn't work. When I switch the line:
data: message,
to
data: [1,4]
it displays correctly. However, I must use a variable. How do I do this?
You declared message variable as STRING, It is expecting an ARRAY
Please change
var message = '[1,4]'
to
var message = [1,4];
I am using the easyautocomplete, http://easyautocomplete.com/, to populate a list as the user types in a search field. The code is as follows:
var options = {
url: function(phrase) {
if (phrase !== "") {
return "http://<url>/todo?query=" + phrase + "&format=json";
} else {
return "http://<url>/todo?query=empty&format=json";
}
},
getValue: "results",
ajaxSettings: {
dataType: "jsonp"
},
requestDelay: 300,
theme: "round"
};
$("#product-list").easyAutocomplete(options);
I am getting a response from my API that looks like:
{
"results": [
"list_item_1",
"list_item_2",
"list_item_3",
...
"list_item_50"
]
}
I have a feeling I'm not formatting the response properly, but I'm not sure how to fix it.
A look through the guide it looks like getValue would be if you had an array of objects and wanted to pull a particular key from each one. From the list location section it looks like you are looking for listLocation to specify the object key that has the array of things to autocomplete. So changing getValue to listLocation should give you the results you are looking for
I have a highstock graph in a file called charts.php that reloads the graph data from a secondary file called data.php. Seeing as I have 5 series in my highstock graph I have to call the data.php file 5 times, each time using a different variable, but when I set the variable in my charts.php file it only uses the last set value of this variable. Is is possible to solve this, or is this just the way PHP works? Do I have to create 5 separate data.php files in order for this to work?
Here's basically what my code looks like (showing 2 series to keep it short):
var chart = new Highcharts.StockChart({
chart: {
renderTo: 'chart'
},
title : { text : 'MyChart' },
series : [
{
name : 'Unit 0',
data : [],
tooltip: { valueDecimals: 1, valueSuffix: ' kW' },
},
{
name : 'Unit 1',
data : [],
tooltip: { valueDecimals: 1, valueSuffix: ' kW' },
}
]
});
<?php $_SESSION["unit"] = 0; ?>
$.getJSON( "data.php", function (data) {
chart.series[0].setData( data );
});
<?php $_SESSION["unit"] = 1; ?>
$.getJSON( "data.php", function (data) {
chart.series[1].setData( data );
});
So the problem is that both series[0] and series[1] use the last value of my variable, which in this case is $_SESSION["unit"] = 1. Is the a way to make this work? Any better alternatives?
Maybe if I could create data for all of the series in one file and somehow split that data and pass it to series[0] and series[1] separately, but I have no idea how to do that..
Any help is appreciated.
Maybe you could modify your data.php file, so instead of using $_SESSION["unit"] to determine which var to use, use $_GET["unit"] instead. Then, in your code above, it would be:
$.getJSON( "data.php?unit=0", function (data) {
chart.series[0].setData( data );
});
$.getJSON( "data.php?unit=1", function (data) {
chart.series[1].setData( data );
});
It depends on your needs, if the $unit values are always the same I would just call data.php once and update all the graphs at once using the JS response.
If $unit has a dynamic variable I would send it along with the $.getJSON function.
var data = {
unit: $_GET['unit']
};
$.getJSON( "data.php", data, function (response) {
updateGraph(graph, response);
});
For more on getJSON on the structure of the function, visit http://api.jquery.com/jquery.getjson/
Below is the structure of JSON which I use to query an API
"order_items": [
{
"menu_item_id": "VD1PIEBIIG",
"menu_item_name": "Create Your Own",
"modifiers": [
{
"modifier_id": "6HEK9TXSBQ",
"modifier_name": "Shrimp"
}
],
"quantity": "1",
"total": 15.99,
"variant_id": "TXDOR7S83E",
"variant_name": "X-Lg 18\""
}
]
Now I want to call this API from an HTML page using Javascript(Using HTML elements like forms and drop down menus etc). I want to create a Javascript object with proper structure and then convert it to JSON using "stringify" function. But I am not able to create the Javascript object. Can anyone help with this?
Like i want to have the following structure
obj.order_items[0].menu_item_id="VD1PIEBIIG";
obj.order_items[0].menu_item_name="Create Your Own";
obj.order_items[0].modifiers[0].modifier_id="6HEK9TXSBQ";
and so on.
var jsonToSend = { "order_items": [ ] };
// then for each order item
var orderItem = { "menu_item_id": <whatever>,
"menu_item_name": <whatever>,
"quantity": <whatever>,
"total": <whatever>,
"variant_id": <whatever>,
"variant_name": <whatever>,
"modifiers": []
};
// then for each modifier
var modifier = { "modifier_id": <whatever>, "modifier_name": <whatever> };
orderItem.modifiers.push(modifier);
jsonToSend.order_items.push(orderItem);
JSON.stringify(jsonToSend);
Well there are a couple of ways to do this.
Manually create the Json object to send from the HTML elements:
$.ajax({
type: "POST",
url: "some.php",
data: new {"order_items": [
{
"total": $('total').Val(),
"variant_id": $('variant_id').Val(),
"variant_name": $('variant_name').Val()
}
]})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
You could use a great framework like KnockoutJs, this will keep your JSON object up to date with your form, so that you don't have to do it manually. When you are ready you just submit your original json back to the server.
See this basic example on JsFiddle
var ClickCounterViewModel = function() {
this.numberOfClicks = ko.observable(0);
this.registerClick = function() {
this.numberOfClicks(this.numberOfClicks() + 1);
};
this.resetClicks = function() {
this.numberOfClicks(0);
};
this.hasClickedTooManyTimes = ko.computed(function() {
return this.numberOfClicks() >= 3;
}, this);
};
ko.applyBindings(new ClickCounterViewModel());
You can use any number of plugins to Serialize the form, but the problem is getting the JSON structure just right.
See SerializeArray
$( "form" ).submit(function( event ) {
console.log( $( this ).serializeArray() );
event.preventDefault();
});
I am ajax calling a php script that outputs two data points
[epoch data, cpu]
I would like to be able to create highchart guage chart and display cpu utilization and as a data lable, I like to display the time that I get from the php call.
function request_cpu_Data() {
$.ajax({
url: 'get_cpu.php',
success: function(data) {
var myObj = JSON.parse(data);
var point = cpu_chart.series[0].points[0];
var point1 = cpu_chart.series[1].points[0];
var newVal=myObj[1];
var newVal1=myObj[0];
point.update(newVal);
point1.update(newVal1);
setTimeout(request_cpu_Data, 10000000);
},
cache: false
});
}
my series options are like this:
series: [{
name: 'CPU',
data: [0]
},{
name: 'Date',
data: []
}
]
I am getting this error:
Uncaught TypeError: Cannot call method 'update' of undefined
Is this how you set up the second series?
var point1 = cpu_chart.series[1].points[0];
Your second series contains no data, so your cpu_chart.series[1].points is an empty array.
You must use setData if data.lenght === 0, like this:
var secondSeries = chart.series[1];
if (secondSeries.data.length === 0) {
secondSeries.setData([newValue]);
} else {
secondSeries.points[0].update(newValue);
}
I hope that will help you.