I have a graph that is properly generated when the page loads. That code is:
<body>
<div id="placeholder" style="width:800px;height:400px;"></div>
<script type="text/javascript">
$(function () {
$.plot($("#placeholder"),
[ { data: %s } ],
{ xaxes: [ { mode: 'time' } ],
yaxes: [ ] })
});
</script>
Which works fine. I have a button that executes jquery and makes a request to get a new json data structure. I've validated that the json being returned is indeed proper json. I'm attempting to graph the result with:
<script type="text/javascript">
$(function() {
$("#button").click( function()
{
//alert('button clicked');
$.ajax({
url: '/graph',
type: 'POST',
dataType: 'html',
data: {
start_date: $('#start_date').val(),
end_date : $('#end_date').val(),
ticker : $('#ticker').val()
},
success: function(result) {
var placeholder = $("#placeholder");
$.plot(placeholder,
[ { data: result } ],
{ xaxes: [ { mode: 'time' } ],
yaxes: [ ] });
}
});
}
);
});
Which redraws the graph, but it's empty and the y-axes is the default -1.0 through 1.0 and the x-axes is a single time entry of 00:00:00.
I've tried to use the setData() and draw() method calls but they don't fix the issue.
There are no javascript errors being thrown as shown by firebug.
So, what am I doing wrong?
TIA!
Are you sure the response is valid? Your dataType is 'html', so unless you're doing something with a script tag, then the response is just a string. If you're returning JSON directly, then you need to use dataType 'json'.
Related
I am trying to load the jQuery DataTable from an AJAX call as in the code below. However I need to know if there is a callback for the DataTable to check if the AJAX call returned successfully or failed before the table is loaded.
$(function() {
$('#data-table').DataTable({
destroy: true,
responsive: true,
serverSide: false,
autoWidth: false,
paging: true,
filter: true,
searching: true,
stateSave: true,
scrollX: true,
lengthMenu: [5, 10, 25, 50, 75, 100],
ajax: {
url: 'https://jsonplaceholder.typicode.com/todos',
type: 'GET',
dataSrc: ''
},
columns: [{
title: 'Zone',
data: 'LastKnownZone',
}, {
title: 'HiƩrarchie Map',
data: 'MapInfo.mapHierarchyString',
}, {
title: 'Addresse MAC',
data: 'macAddress',
}],
initComplete: function(json) {
let returned_data = json;
//..Do something with data returned
}
});
});
Appreciate any help.
Just adding something to #Fawaz Ibrahim's answer, it's also better to add error option in Ajax call in order to check if you face any error or problem , because in case of error, dataSrc callback won't run, so you won't have any successful returned data.
ajax: {
...
dataSrc: function ( receivedData ) {
console.log('The data has arrived'); // Here you can know that the data has been received
return receivedData;
},
error: function (xhr, error, thrown) {
console.log('here you can track the error');
}
}
As it is mentioned on their official site:
For completeness of our Ajax loading discussion, it is worth stating
that at this time DataTables unfortunately does not support
configuration via Ajax. This is something that will be reviewed in
future
But you can use the idea of datasrc, like this:
$(function() {
$('#data-table').DataTable({
...
ajax: {
...
dataSrc: function ( receivedData ) {
console.log('The data has arrived'); // Here you can know that the data has been received
return receivedData;
}
},
...
});
});
I've put together some code which allows me to query a MySQL database, return the result and populate a chart.js. The problem being that each time the AJAX code runs the chart is rendered over the previous one. I've read through a few similar stackoverflow queries which are recommending the use of myChart.destroy(); or other solutions but I' struggling to work out where this should be inserted into the following code.
Note that I've simplified the code below for simplicity sake.
Any assistance on how to stop this chart 'ghosting' occuring would be greatly appreciated.
<script type="text/javascript">
jQuery(document).ready( function($) {
var valueCheck;
jQuery('#afl_player_year').on( 'change', function () {
afl_player_year = $('#afl_player_year').val();
jQuery.ajax({
type: "POST",
url: "/wp-admin/admin-ajax.php",
dataType: "json",
data: {
action: 'call_player_chart_data',
afl_player_year: afl_player_year,
},
success:function(output){
var y_data1 = output[0];
var y_data2 = output[1];
var x_time = ............
new Chart(document.getElementById("myChart"), {
type: 'bar',
data: {
labels: x_time,
datasets: [{.........
}, {.........
}]
},
options: {
scales: {.........
yAxes: [{.........},{.........},
}]
}
}
});
}
});
}).change();
});
</script>
I have a controller action in my MVC project that creates a json record with the components needed. This is working. The issue I am having is bringing it into a chart.js canvas. This will be a pie chart that shows all the related countries with a count of each. Json has this info. Originally this was setup to use google visualization but I want to use chart.js. I just started using it. Creating charts with static data is no issue but I am pulling the info from a SQL table and creating a json to read from.
I have tried using the same structure and calling the data: data[] but it doesn't work I have also tried data: getData, which is a var for the ajax function. I am getting the data per the council on refresh.
Here is my controller Action
public ActionResult CustomersByCountry()
{
CustomerEntities _context = new CustomerEntities();
var customerByCountry = (from c in _context.Addresses
group c by c.Country into g
orderby g.Count() descending
select new
{
Country = g.Key,
CountCustomer = g.Count()
}).ToList();
return Json(new { result = customerByCountry }, JsonRequestBehavior.AllowGet);
}
And here is the JavaScript/ajax - which is nested in a document.ready function with the rest of the charts.
EDIT - changed Ajax - Still not working
OrdersByCountry()
function OrdersByCountry() {
$.ajax({
url: '/admin/CustomersByCountry',
method: "GET",
dataType: "json",
error: function (_, err) {
console.log(_, err)
},
success: function (data) {
console.log (data);
var customer = $("#customerByCountryPieChart").get(0).getContext("2d");
console.log(customer)
var cpieChart = new Chart(customer, {
type: 'pie',
data: data,
options: {
responsive: true,
title: {
display: true,
text: "Customers By Country",
}
}
});
}
});
};
Edit - The now working code is below.
I changed it to get states instead of country, just to clear up possible confusion. It made more sense to me to get States rather than Country at this point. This is working - meaning displaying the graph, I still need to work on the labels etc.
OrdersByStates()
function OrdersByStates() {
$.ajax({
url: '#Url.Action("CustomersByStates", "Admin")',
data: JSON,
contentType: "application/json; charset=utf-8",
method: "get",
dataType: "json",
error: function (_, err) {
console.log(_, err)
},
success: function (response) {
console.log(response);
var jsonresult = response
var labels = jsonresult.result.map(function (e) {
return e.State;
});
var data = jsonresult.result.map(function (e) {
return e.CountCustomer;
});;
var ctx = document.getElementById("CustomerByStatePieChart").getContext("2d");
var cpieChart = new Chart(ctx, {
type: 'pie',
data:
{
datasets: [
{
backgroundColor: ["#46BFBD", "#F7464A"],
hoverBackgroundColor: ["#5AD3D1", "#FF5A5E"],
label: "Orders",
data: data,
}]
},
options: {
responsive: true,
title: {
display: true,
text: "Customers By Country",
}
}
});
}
});
};
});
try:
var cpieChart = new Chart(customer, {
type: 'pie',
data: data.result,
options: {
responsive: true,
title: {
display: true,
text: "Customers By Country",
}
}
});
the response from the server "data" var on your request is {result: LIST}
I am having a problem with some code. Here is what the JSON response looks like:
{"cars":"1","bikes":"1"}
Here is the jQuery code:
$(function() {
$.getJSON('https://myurlhere.com?filename=aapl-c.json&callback=?', function(data) {
// Create the chart
$('#container').highcharts('StockChart', {
rangeSelector: {
selected: 1
},
title: {
text: 'AAPL Stock Price'
},
series: [{
name: 'AAPL',
data: data,
tooltip: {
valueDecimals: 2
}
}]
});
});
});
Here is the error I'm getting:
SyntaxError: missing ; before statement {"cars":"1","bikes":"1"}
What am I doing wrong here?
From the $.getJSON documentation:
If the URL includes the string "callback=?" (or similar, as defined by the server-side API), the request is treated as JSONP instead.
This is the cause of your problem as your return data is in JSON format, not JSONP. You just need to remove that property from the querystring of the request:
$.getJSON('https://myurlhere.com?filename=aapl-c.json', function (data) {
// the rest of your code...
});
i have three files index.html , getData.php and data.json
index.html ->
<script type="text/javascript">
function load() {
var jsonData = $.ajax({
url: "getData.php",
type: "GET",
data: {variable: "loadavg"},
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, {width: 800, height: 400});
}
</script>
<ul class="list">
<p>Load average <input id="loadAvg" type="button" value="Enter" onclick="load();" /> </p>
</ul>
getData.php ->
<?php
// It reads a json formatted text file and outputs it.
if(isset($_GET["variable"]) == "loadavg"){
$string = file_get_contents("data.json");
echo $string;
// if this works you should see in console 'graph on cosole'
}
?>
data.json ->
{
"cols": [
{"id":"","label":"HostName","type":"string"},
{"id":"","label":"CPU","type":"number"},
{"id":"","label":"Free Avg memory","type":"number"}
],
"rows": [
{"c":[{"v":"lp10b2vapp01,w10"},{"v":21}]},
{"c":[{"v":"lp10b2vapp01,w10"},{"v":15}]},
{"c":[{"v":"lp10b2vapp01,w10"},{"v":73}]},
{"c":[{"v":"lp10b2vapp01,w10"},{"v":60}]},
{"c":[{"v":"lp10b2vapp01,w10"},{"v":48}]},
{"c":[{"v":"lp10b2vapp01,w10"},{"v":40}]},
{"c":[{"v":"lp10b2vapp01,w10"},{"v":36}]}
]
}
when i click on button i was unable to see the output (Graph) ,Kindly look help me
Thanks in advance
Don't use async: false. It's terribly bad practice as it locks the UI thread making the browser look to the user like it has crashed until the request completes. Instead use the async callbacks which $.ajax provides you to update the UI of the page once the request has finished. Try this:
function load() {
$.ajax({
url: "getData.php",
type: "GET",
data: {
variable: "loadavg"
},
dataType: "json",
success: function(jsonData) {
var data = new google.visualization.DataTable(jsonData);
var chart = new google.visualization.ColumnChart($('#chart_div')[0]);
chart.draw(data, {
width: 800,
height: 400
});
}
});
}
Also note that you need to get the value of the parameter in the PHP code as well as checking it exists:
if (isset($_GET["variable"]) && $_GET["variable"] == "loadavg")
{
// code here...
}