Load data into Highcharts with Ajax - ajax

I am trying to update high charts on page load and on select menu change with JQUERY AJAX call. There is data being returned in [[10,1228800000],[10,1228800000]] format.The chart is blank and does not graph any of the data.
Tried several solutions posted on here but none worked.
var chart;
$(document).ready(function() {
var options = {
chart: {
renderTo: 'stats',
defaultSeriesType: 'spline'
},
title: {text:''},
xAxis: {
type: 'datetime'
},
yAxis: {},
series: []
};
var month = 'July';
$.ajax({
type: "POST",
data: "month="+month,
url: "update_visits_chart",
success: function (data) {
options.series.push(data);
chart = new Highcharts.Chart(options);
}
});
Any errors? thanks in advance.
EDIT:
MOST RECENT CODE STILL NOT WORKING:
var options = {
chart: {
renderTo: 'stats',
type: 'spline'
},
title: {
text: ''
},
xAxis: {
type:'datetime',
tickInterval: 30 * 24 * 3600 * 1000,
dateTimeLabelFormats: {
day: '%b %e'
},
labels: {
rotation: -45,
align: 'right'
}
},
yAxis: {
title: {
text: 'Number of visits'
},
min: 0
},
tooltip: {
formatter: function() {
return Highcharts.dateFormat('%b %e', this.x) +'<br />'+this.y+' visit(s)';
}
},
legend: {
enabled: true
},
credits: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
name: 'Number of Visits',
data: []
}]
};
var month = 'July';
$.ajax({
type: "POST",
url: "update_visits_chart",
data: "month="+month,
success: function(data){
options.series[0].data = data;
chart = new Highcharts.Chart(options);
}
});

You have to use the setData methode of the series object as descriped in documentation. In your case it is options.series[0].setData(Data)
And I think you have to turn your Ajax result from string to a real object/array by using JSON.parse(data).
EDIT:
#Ricardo Lohmann: in the ajax-call he did not specify the dataType he expects in the response, so jQuery will guess the dataType. But it will not recognize a string starting with [ as JSON and I doubt his response will be served with correct mime type application/json. So specifying the correct mime type should also solve the problem. But I do not have an example of the complete ajax respons of the questioner. So I'm just guessing, too.
I'd recommend the following ajax call:
$.ajax({
type: "POST",
url: "update_visits_chart",
data: {month: month},
dataType: 'json',
success: function(data){
options.series[0].setData(data);
}
});
#Jugal Thakkar
$.getJSON is just a shortcut for the ajax-call above, but it is less flexible because you have less options.

You have to set directly data to series because data is already a multidimensional array.
The following code will fix it.
Change options.series.push(data); to options.series = data;

Related

Loading AJAX Data on ShieldUI Data Grid

I just want to share how I was able to load the Data from AJAX Request into ShieldUI DataGrid,
I didn't see any related post which has direct and clear answer so I thought maybe someone can use this as a guide.
$(document).ready(function(){
$("#shieldui-grid1").shieldGrid({
dataSource: {
data: gridData
},
selection: {
type: "row",
multiple: true,
toggle: false
},
columns: [
{
field: "product_name", width: "30%", title: "Product Name"
},
{
field: "source_name", title: "Source Name", width: "30%"
}
]
});
});
var gridData = function() {
$.ajax({
async: false,
url: "/your-api-url",
dataType: 'json',
type: 'GET',
success: function(data){
console.log(data);
gridData = data;
}
});
return gridData;
}();
});
This will automatically pickup the data result from the Ajax request assigned into 'gridData' variable
I was able to pass the result into the gridData variable using this,
var gridData = function() {
$.ajax({
async: false,
url: "/your-api-url",
dataType: 'json',
type: 'GET',
success: function(data){
console.log(data);
gridData = data;
}
});
return gridData;
}();
Shield UI Grid demos have examples of this - namely, how to connect to a RESTful and similar web services.

Change Kendo Grid Cell With Ajax Response When Another Cell Changes

Using a Kendo grid with 3 columns, I have an event that fires when the first column is changed that makes an ajax call and returns some data. I want to update the second column with the returned data but I'm not having any luck and I'm not even sure if this is the correct approach. I can change the second column with static data by adding a change event to my datasource of my grid, but that of course doesn't help. The only examples I can seem to find show changing another column with client side data, not data returned from the server. Here's what I have so far:
$("#manualStatsGrid").kendoGrid({
dataSource: this.GetManualStatisticsDataSource(),
sortable: true,
pageable: false,
filterable: true,
toolbar: ["create"],
editable: "inline",
messages: {
commands: {
create: "Add New Statistic"
}
},
edit: function (e) {
var _this = _manualStats;
var input = e.container.find(".k-input");
var value = input.val();
input.keyup(function(){
value = input.val();
});
$("[name='Statistic']", e.container).blur(function(){
var input = $(this);
$("#log").html(input.attr('name') + " blurred " + value);
//valid the GL account number
$.ajax({
type: "GET",
url: _this.ValidateGlUrl,
dataType: 'json',
data: { glNumber: value },
success: function (response) {
var newDescription = response.Data.description;
console.log(newDescription);
//change description column here?
},
error: function (response) {
console.log(response);
}
});
});
},
columns: [
{ field: "Statistic" },
{ field: "Description" },
{ field: "Instructions" },
{ command: ["edit", "destroy"], title: " ", width: "250px"}
]
});
}
this.GetManualStatisticsDataSource = function () {
var _this = _manualStats;
var dataSource = {
type: "json",
transport: {
read: {
type: "POST",
url: _this.GetManualStatisticsUrl,
dataType: "json"
},
update: {
type: "POST",
url: _this.UpdateManualStatisticsUrl,
dataType: "json"
},
create: {
type: "POST",
url: _this.CreateManualStatisticsUrl,
dataType: "json"
},
destroy: {
type: "POST",
url: _this.DeleteManualStatisticsUrl,
dataType: "json"
}
},
schema: {
model: {
id: "Statistic",
fields: {
Statistic: {
type: "string",
editable: true,
validation: { required: true, pattern: "[0-9]{5}.[0-9]{3}", validationmessage: "Please use the following format: #####.###" }
},
Description: { editable: false },
Instructions: { type: "string", editable: true }
}
}
}
Inside the edit event, you have e.model. The model has the method set() which can change any dataItem's property value:
edit: function (e) {
...
var editEvent = e; // Creates a local var with the edit's event 'e' variable to be available inside the 'blur' event
$("[name='Statistic']", e.container).blur(function() {
...
$.ajax({
...
success: function(e, response) { // 'e' inside this callback is the 'editEvent' variable
e.model.set("Description", response.Data.description); // e.model.set() will change any model's property you want
}.bind(null, editEvent) // Binds the 'editEvent' variable to the success param
});
});
Working demo
Made this snippet of top of my head. Tell me if there is something wrong with it.

fullcalendar pass in array to set events

I would like to pass in an array of IDs that will be used to select the events I want to display. The fullcalendar displays all of the events if I do not use the 'data' attribute with the ID array. When the data attribute is added I get the error message 'There was an error fetching events!'
This is the document ready function:
var groupSelectedArray = [];
groupSelectedArray[0] = '1';
groupSelectedArray[1] = '2';
$('#calendar').fullCalendar({
header:
{
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
titleFormat: {month: 'MMMM'},
defaultView: 'month',
editable: false,
events: function (start, end, groupSelectedArray, callback) {
$.ajax({
type: "POST",
url: '#Url.Action("GetAllEvents", "Home")',
data: { selectedGroups: groupSelectedArray },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (doc) {
var events = [];
$(doc).each(function () {
events.push({
title: $(this).attr('title'),
start: $(this).attr('start'),
end: $(this).attr('end'),
id: $(this).attr('id'),
description: $(this).attr('description'),
color: $(this).attr('color'),
textColor: 'black'
});
});
callback(events);
} ,
error: function () {
alert("There was an error fetching events!")
}
});
}
This is the C# method:
public JsonResult GetAllEvents(string[] selectedGroups)
{
var eventList = GetEventsFromDatabase(selectedGroups);
var rows = eventList.ToArray();
return Json(rows, JsonRequestBehavior.AllowGet);
}
Can anyone see where I am going wrong?
Thanks.
What I did to get this to work was change the 'data' part of the ajax call:
Replace this:
{ selectedGroups: groupSelectedArray },
to this:
data: JSON.stringify(groupData),

jQuery ui autocomplte in jQGrid popup position issue

I have following code in jQgrid and I am using jQuery ui autocomplete in one of the field. But the pop up of autocomplete displays somewhere else as shown in figure. From IE developer tools I noticed the results are attached to body tag, which is at the end of the page. I tried using appendTo, but that doesn't help.
{
name: 'nameAccount',
index: 'nameAccount',
width: 300,
editable: true, sortable: false, resizable: false,
shrinkToFit: true
,editoptions: {
dataInit: function (elem) {
var autocompleteSource = function(request, response,term) {
var param = request.term;
$.ajax({
url: myUrl,
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "GET",
success: function (myyydata) {
//alert('HI-Success');
//response( myyydata );
response($.map(myyydata, function (item) {
return {
label: item.AccountInfo,
value: item.AccountInfo
}
}));
} ,
error: function (res, status) {
alert('HI-error');
//alert(res.status+" : "+res.statusText+". Status: "+status);
}
});//END AJAX
};
$(elem).autocomplete({
source: autocompleteSource,
//appendTo: "#"+elem.id,
position: { collision: "flip" },
minLength: 2
});//END AUOTOCOMPLETE
}//END Dataint
}//END Dataint
},
minnu4515. i guess it is because of the css misalignment. i faced the similar problem and i manually set the z-index alignmnet. that solved my issue.
$('.ui-autocomplete').css('zIndex',1000);

Dynamic Flot chart using Ajax

I'm new to javascript and flot and hope someone can help me with this problem I'm having.
What I'm trying to achieve it have a dynamic flot graph on a page.
The data for the series that is to be plotted is in a file that will get updated every few seconds. I want the flot graph to read the data file every few seconds and be updated with the new data.
Here's the code I've got which isn't working. The graph displays ok on page load, but just doesn't get updated every 5 seconds.
Any help is much appreciated.
$(function () {
var dataFolder = "http://localhost/graphdata/";
/***********************************************************************
* Function to get series data from a file
***********************************************************************/
function getSeriesData(file) {
var url= dataFolder + file;
var data = null;
$.ajax({
async: false,
url: url,
method: 'GET',
dataType: 'json',
success: function(datasets){
data = datasets;
},
error: function(error,text,http){
alert(error + " " + text + " " + http);
}
});
return data;
}
var plot = $.plot($("#placeholder"),
[
{label: "A", data: getSeriesData("dataA.txt")},
{label: "B", data: getSeriesData("dataB.txt")},
{label: "C", data: getSeriesData("dataC.txt")}
],
{
series: {
lines: {
color: "red",
show: true
},
points: {
show: true
},
shadowSize: 0,
hoverable: true
},
colors: ["red", "blue", "green"],
yaxis: {
min: 0, ticks:5
},
xaxis: {
mode: 'time',
timeformat: '%H:%m',
show: false
},
legend:{
show: true
},
grid:{
color: "green",
show: true,
backgroundColor: "white",
hoverable: true
}
}
);
var updateInterval = 1000 * 5;
function update() {
plot.setData([
{label: "A", data: getSeriesData("dataA.txt")},
{label: "B", data: getSeriesData("dataB.txt")},
{label: "C", data: getSeriesData("dataC.txt")}
]);
plot.setupGrid();
plot.draw();
setTimeout(update, updateInterval);
}
update();});
I figured it out. The ajax call for the file was being cached in the browser so any further calls for the same file would have been returned from cache, making it look like no updates to the graph were happening. Switch caching of in the function and it works fine now.
function getSeriesData(file) {
var url= dataFolder + file;
var data = null;
$.ajax({
async: false,
cache: false,
url: url,
method: 'GET',
dataType: 'json',
success: function(datasets){
data = datasets;
},
error: function(error,text,http){
alert(error + " " + text + " " + http);
}
});
return data;
}
It seems to update correctly for me using numbers. Can you provide a few data examples?
I changed the x axis and data pull but the updating worked fine.
function getSeriesData() {
var randomnumber=Math.floor(Math.random()*11)
var randomnumber2=Math.floor(Math.random()*11)
var data = [
[randomnumber, randomnumber2],
[randomnumber +1, randomnumber2 +2],
[randomnumber +3, randomnumber2 +4],
[randomnumber +5, randomnumber2 +6],
[randomnumber +7, randomnumber2 +8],
];
return data;
}
fiddle - http://jsfiddle.net/EX6dv/1/
It seems you need to put following out side the update function too.
setTimeout(update, updateInterval);

Resources