I'm quite a newbie concerning JS, so this may be a stupid question...
I try to do a Highscore Master/Detail chart (see sample http://jsfiddle.net/VhqaQ/). The data array should be filled with a jQuery.ajax call:
$(function () {
var masterChart,
detailChart,
data=[],
chatter=[],
indizies=[];
$(document).ready(function() {
$.ajax({
url: 'index.php',
data: 'type=1363435001',
dataType: 'json',
success: function(json) {
data = json.range;
scatter = json.scatter;
indizies = json.indizies;
},
error: function (xhr, status, error) {
alert('Status: ' + status +' Error: ' + error);
}
});
// create the master chart
function createMaster() {
masterChart = new Highcharts.Chart({
.......
series: [{
type: 'columnrange',
name: 'Intervall',
pointInterval: 1,
pointStart: 0,
data: data
}],
});
}
........
createMaster();
});
});
But like this the chart stays empty. Is this a scope issue for the data array? Or is data not initialized yet when new Highcharts.Chart( ...) is called?
I tested the ajax part - data is filled properly. So this is not the issue...
Maybe I should put the ajax call somewhere else?
Call createMaster() in the callback of your $.ajax call and pass it the data.
You are currently assuming that at initialization of the ajax call that the data has been returned, which most likely not the case. Placing the function call inside of the callback ensure that your data is present.
$.ajax({
url: 'index.php',
data: 'type=1363435001',
dataType: 'json',
success: function(json) {
data = json.range;
scatter = json.scatter;
indizies = json.indizies;
createMaster(data);
},
error: function (xhr, status, error) {
alert('Status: ' + status +' Error: ' + error);
}
});
// create the master chart
function createMaster(data) {
masterChart = new Highcharts.Chart({
.......
series: [{
type: 'columnrange',
name: 'Intervall',
pointInterval: 1,
pointStart: 0,
data: data
}],
});
}
Related
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 have a situation in which i m trying to create events dynamically using the plugin fullcalendar im trying to create events with the help of the ajax call and the data retrieved is in the form of json
when i m trying to create events only event at index 0 is getting created rest of events are not created
the javascript code is as follows
function showData()
{
var ids = showValidData();
if (ids.length != 0)
{
$.ajax({
url: $("#base-url").val() ,
type: 'POST',
data: {'ids': ids},
dataType: 'json',
success: function (response)
{
var data = response.data;
var myevents = [];
if (response.success)
{
$(data).each(function (index, value) {
myevents.push({
title: value.layoutName,
start: value.startDate,
end: value.endDate
});
});
console.log(myevents);
$(".fc-event-container").click();
$('#calendar-example-1').fullCalendar({
events: myevents,});
return;
}
}
});
}
}
Set events when initializing FullCalendar - define the url of the script that returns a json of events from your database (https://fullcalendar.io/docs/event_data/events_function/). If you want to dynamically refresh the calendar , you can add a setInterval ontop:
$(document).ready(function(){
setInterval(function(){$('#calendar').fullCalendar('refetchEvents')}, 30000);
$("#calendar").fullCalendar({
...
events: {
url: 'script.php',
type: 'POST',
data: {
data1: x,
data2: y
},
success : function(response){
// do something
},
}
});
});
I have several different charts that I am rendering with c3js via ajax, and I currently have a lot of repeated ajax code that I would like to cut down on.
Each ajax call on success generates a c3js chart, but with different display types/options. Is there a way I can have a generic c3js generate and just pass in the options?
$.ajax({
url: url,
data: {'chart': chart, 'start': start, 'end': end},
type: 'post',
dataType: 'json',
beforeSend: function () {
//code
},
success: function (data) {
if (data.success) {
//code
c3.generate({
bindto: '#chart-data',
data: {
columns: data.active,
type: 'area',
groups: [data.groups]
},
axis: {
x: {
type: 'category',
categories: data.span
},
y: {
label: 'Label'
}
}
});
} else {
//code
}
}
});
Repeated several times with various chart data types, groups, columns, axis, etc.
What I want:
var chart_options = {bindto: '#chart-data', data:{columns.data.active} //...
function generateChart(param1, param2, param3, chart_options) {
//do some stuff
//ajax call from above
// ....
// on success:
// c3.generate(chart_options)
}
However when I do it this way, because the data.success is inside the function, and I am passing columns: data.active from outside the function, I receive javascript errors for data[i] column not defined.
Thanks
var chart_options = {bindto: '#chart-data', {data: {type: "area"}} //...}
function generateChart(param1, param2, param3) {
//do some stuff
//ajax call from above
// ....
// on success:
// chart_options.data.colums = data.active;
// chart_options.data.groups = [data.groups];
// same for axes…
// c3.generate(chart_options)
}
I've configured my FullCalendar to pull its events from an AJAX request, but they don't render on the calendar when the page is first loaded.
$(document).ready(function() {
sh1client = new Array();
sh2client = new Array();
$('#sh1_cal').fullCalendar({
height: 1000,
minTime:'9:00am',
maxTime:'5:00pm',
editable: false,
events: function(start, end, callback) {
$.ajax({
type: 'GET',
url: 'http://localhost:8080/getEvents',
dataType: 'json',
success: function(reply) {
console.log(reply.first);
callback(reply.first);
}
});
}
});
$("#sh1_cal").fullCalendar('addEventSource', sh1client); // these are the clientside arrays
});
And on the server,
app.get('/getEvents', function(req, res){
console.log('Server: passing events...');
var arrays = {first: sh1, second: sh2}
var pack = JSON.stringify(arrays)
res.writeHead(200, {'Access-Control-Allow-Origin' : '*', 'Content-Type': 'application/json'});
res.end(pack);
});
Is there any reason these events wouldn't initially load? Everything seems to be being passed through alright, but it's like the callback isn't working or something.
EDIT: Here is another approach I tried
events: {
url: 'http://localhost:8080/getEvents',
type: 'GET',
error: function() {
alert('there was an error while fetching events!');
},
success: function(reply) {
console.log(reply);
//callback(reply.first);
},
color: 'yellow', // a non-ajax option
textColor: 'black' // a non-ajax option
}
EDIT: JavaScript console shows this as being POSTed to the page as soon as it loads (this is the first object in an array:
[Object]
allDay: "false"
end: "1392129000"
id: "phil#google.com"
room: "Sh1"
start: "1392127200"
title: "Phil - Google"
__proto__: Object
length: 1
__proto__: Array[0]
Instead of using your own ajax call, have you tried using fullcalendars?
http://arshaw.com/fullcalendar/docs/event_data/events_json_feed/
Fullcalendar defaults the dataType as JSON and caching to false.
Combined some of your code with code from doc:
$('#calendar').fullCalendar({
events: {
url: 'http://localhost:8080/getEvents',
type: 'GET',
error: function() {
alert('there was an error while fetching events!');
},
success: function(reply) {
console.log(reply.first);
callback(reply.first);
},
color: 'yellow', // a non-ajax option
textColor: 'black' // a non-ajax option
}
});
You can try just getting your JSON string cutting and pasting in and see if you can render without ajax call
events: [
{
end: 1392129000,
id: "phil#google.com",
room: "Sh1",
start: 1392127200,
title: "Phil - Google"
}]
You can also process the response:
$('#myCalendar').fullCalendar({
...
eventSources : [{
url: 'myUrl',
type: 'GET',
},
success: function(replyObject) {
var results = [];
var reply= replyObject.Results[0];
for(var index in reply) {
results.push(reply[index]);
}
return results;
}
}]
...
I am looking to populate my grid with JSON data. The data is in the below format:
[{
"SiteId":"1",
"SiteName":"University of Minessota",
"SiteStatus":"Fully Operational"
},{
"SiteId":"2",
"SiteName":"MSP Airport-Humphrey",
"SiteStatus":"Settlement Required"
},{
"SiteId":"3",
"SiteName":"City Of Minneapolis-Lot C",
"SiteStatus":"Fully Operational"
},{
"SiteId":"4",
"SiteName":"TargetCenter",
"SiteStatus":"Low Tickets"
},{
"SiteId":"5",
"SiteName":"Excel Energy Center",
"SiteStatus":"Out Of Tickets"
}]
and i am passing this to the view using my controller method:
public JsonResult StatusReport()
{
List<CenterStatus> status = MvcList.Models.CenterStatus.GetStatus();
return this.Json(status, JsonRequestBehavior.AllowGet);
}
Now in my view I need to populate this JSON data into a grid:
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "CenterStatus/StatusReport.aspx",
data: "{}",
dataType: "json",
success: function (data) {
for (var i = 0; i < data.d.length; i++) {
$("#GridView1").append("<tr><td>" + data.d[i].siteID + "</td><td>" + data.d[i].siteName + "</td><td>" + data.d[i].siteStatus + "</td></tr>");
}
},
error: function (result) {
alert("Error");
}
});
But I have no luck in achieving my goal so far. Any suggestions?
Do it like this. do not call append in a loop. Set it to a variable and call the html function only once.
success: function (data) {
var row=""
$.each(data,function(index,item){
row+="<tr><td>"+item.SiteName+"</td></tr>";
});
$("#GridView1").html(row);
},
Working sample : http://jsfiddle.net/x76LD/1/
May be you should use just data instead of data.d in your success function.
I'm guessing the url: "CenterStatus/StatusReport.aspx", might have something to do with it. The correct url should probably be:
url: "/CenterStatus/StatusReport"