load c3 chart with remote data - ajax

How can I load the chart with remote data using ajax request returning JSON encoded data?
Coding snippet:
var chart = c3.generate({
bindto:"#chartdivObservation",
data: {
columns: [
['loading', 30, 20, 50, 40, 60, 50],
]
}
});
$(document).on("change","#getObservation",function(){
var team_id=$(this).val();
var user_id=<?=$userId?>;
$.ajax({
url:"ajax/user/getDeltaStats.php",
type:"POST",
data:{
get:"getObservationReport",
teamId:team_id,
userId:user_id
},
success:function(response){
var data = $.trim(response)
setTimeout(function(){
chart.unload('loading');
console.log("loading chart...")
console.log(data)
chart.load({columns: data})
}, 4500)
console.log(chart)
}
});
});
The first column "loading" is the dummy data, so that the chart is rendered. Later, using timeout I'm loading it with new data (reference http://c3js.org/samples/data_load.html). But, the chart isn't getting rendered with the new data.
The response generated by the ajax request is:
[["Agenda",90,70,70,20,40,70,60,60,58,63],["Precise Praise",53,60,80,68,80,60],["Circulation & Radar",70,100,93,60,100,90,73,90,75,45,60,60,80,73,60]]

Here is an example which works fine for my application. Maybe that helps.
$(document).on("click", "#btnPDquant", function(event) {
$.ajax({
url: "PDQuantCalc",
type: "post",
data: $('#formPDquant').serialize(),
success: function(response){
var newdat = JSON.parse(response);
$("#divPDquant").text(newdat.PDquant[1]);
chart.x(newdat.year);
chart.load({
columns: [ newdat.PDquant ]
});
},
error: function (response) {
$("#divPDquant").text("error");}
});
event.preventDefault(); // Important! Prevents submitting the form.
});

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.

jQuery.ajax request progress bar

Okay, this is the same post as my last post which got downvoted and marked as duplicate. Here's the post again but now with the explaination why the questions from What is the cleanest way to get the progress of JQuery ajax request? didn't work.
I have an AJAX request in where I insert stuff in the database and send 2
emails. I'd like to show the progress of the AJAX request.
Currently I tried:
$.ajax({
type: 'POST',
url: '/ajax/submit_order_form.php',
data: form_data,
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.addEventListener('progress', function(e) {
if (e.lengthComputable) {
$('title').html((100 * e.loaded / e.total) + '%');
}
});
return xhr;
},
complete: function() { /*here some stuff*/ }
});
However, it doesn't change the title during the request, but after the request it sets it to 100%. Is there any way I can get what I want? So that when 50% in the AJAX file is executed it shows 50% and does the progress like that.
The next thing I tried is:
$.ajax({
type: 'POST',
url: '/ajax/submit_order_form.php',
data: form_data,
chunking: true,
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
$('title').html(percentComplete);
//Do something with upload progress here
}
}, false);
xhr.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
$('title').html(percentComplete);
//Do something with download progress
}
}, false);
return xhr;
},
complete: function (result){}});
However then I only get a 1 in the title, and immediately when I click my button and the AJAX gets called.
Last, I tried the second answer:
$.ajax({
type: 'POST',
url: '/ajax/submit_order_form.php',
data: form_data,
chunking: true,
complete: function (result) {}
}).progress(function(e, part) {
console.log(part);
}).progressUpload(function()
{
});
However this gives:
jq-ajax-progress.min.js:1 Uncaught TypeError: Cannot read property 'upload' of undefined
at Function.e.ajax (jq-ajax-progress.min.js:1)
at a.validator.submitOrderForm (checkout.js:108)
at d (jquery.validate.min.js:4)
at HTMLFormElement.<anonymous> (jquery.validate.min.js:4)
at HTMLFormElement.dispatch (jquery.min.js:3)
at HTMLFormElement.r.handle (jquery.min.js:3)
I tried a lot of things already but none seem to work.

Backbone - rest POST service is called more than once

I have a problem when I call a REST service by POST to updates tables in MySQL.
I'm working with BackboneJS and when click Save button, call the service and passed POST parameters
$.ajax({
type: 'POST',
url: rootURL,
data: dataJson, //data send to REST service by POST
cacheControl: "no-cache",
dataType: "json",
success: function(data){
console.log("OK");
},
error: function(data){
console.log(data.msg);
}
});
But the problem occurs when income and leave the editing screen. Assuming I made a change and it worked perfectly bringing me back a single "OK", when I go back into the editing screen and record again, I get twice the word "OK".
If I repeat this step to enter and exit the screen edition, duplicate responses are based on the number of times into the screen edition.
I don't know if it's a problem about I'm doing wrong with BackboneJS...?? I'm doing this:
editAdverts: function(){
var editAdvertsView = new EditAdvertsView ();
$('#container-page').append(editAdvertsView.render(idAdverts).el);
}
It can also be a topic of AJAX?
I hope someone can help me with this issue because I am not an expert in BackboneJS
Thanks a lot!
Diego
It's hard to tell without more code but I'm pretty sure it's because you are creating a model each time you are using editAdvert.
Instead of creating a model each time just create one at the init of your view then call the fetch/save function anytime you need an update. Creating the model once is enough.
edit: zombies views is a good thing to check too as brent noticed in comment, we can't tell without more code.
This is de code about route:
var Index = {
start: function() {
var list_view = new MainView();
}
};
var AppRouter = Backbone.Router.extend ({
routes: {
'goAdvert' : 'goAdvert'
},
goAdvert: function(){
var viewAdvertsView = new ViewAdvertsView();
$('#container-page').append(viewAdvertsView.render().el);
}
});
var MainView= Backbone.View.extend({
el: $('#contenedor-body'),
initialize: function() {
this.render();
},
render: function() {
// here is the code about main page. It's not important!
},
});
new AppRouter;
Index.start();
Backbone.history.start();
This is the viewAdvertsView.js
define([
'jquery',
'underscore',
'backbone',
'jqueryuniform',
'bootstrap',
'handlebars',
'jqueryDataTables',
'dtBootstrap',
'../../view/editAdvertsView',
], function($, _, Backbone, jqueryuniform, Bootstrap, Handlebars, JQueryDataTables, DtBootstrap, EditAdvertsView){
var viewAdverts = Backbone.View.extend({
events: {
'click #edit' : 'editAdvert'
}
editAdvert: function(){
$('#container-page').empty();
var idAdvert = $(event.target).data('id');
editAdvertView = new EditAdvertsView();
$('#container-page').append(editAdvertView.render(idAdvert).el);
},
render: function() {
// load viewAdverts
}
});
return viewAdverts;
}
);
And this is editAdvertsView.js
define([
'jquery',
'underscore',
'backbone',
'jqueryuniform',
'bootstrap',
'handlebars',
'jqueryDataTables',
'functions',
'sessionManage',
'slimscroll',
'jqueryCustomSlimscroll',
'slimscrollMin',
'jqueryblockui',
'text!../../html/editAdverts.html',
'maps',
'fancybox'
], function($, _, Backbone, jqueryuniform, Bootstrap, Handlebars, JQueryDataTables,
Functions, SessionManage, Slimscroll, JqueryCustomSlimscroll, SlimscrollMin,
Jqueryblockui, EditAdverts, Maps, Fancybox){
var Advert= Backbone.View.extend({
el: $('#container-page'),
events: {
'click #saveChanges' : 'doSaveChanges'
},
doSaveChanges: function(){
var data = null;
var rootURL = "http://localhost/php/slim/slim/advert/update" + "?date=" + $.now();
dataJson = {
id: $("#id").val(),
product: $("#product").val(),
price: $("#price").val(),
client: $("#client").val(),
country: $("#country").val(),
tel: $("#telephone").val(),
cel: $("#cellphone").val()
};
$.ajax({
type: 'POST',
url: rootURL,
data: dataJson,
cacheControl: "no-cache",
dataType: "json",
success: function(data){
console.log("OK");
error: function(data){
console.log(data.msg);
}
}
},
render: function(codInmueble) {
var self = this;
var editTemplate = Handlebars.compile(EditAdverts);
self.$el.html(editTemplate());
return this;
}
});
return Advert;
}
);

How can I load all events on calendar using Ajax?

I want to load all events on FullCalendar using AJAX when I clicked next-previous-button in agenda-views.
I guess, when will click on next-previous-button then I'll send current date('y-m-d') to url: 'fetch-events.php' then it will return event{ id: ,title: , start: , end: , allDay: } format data for rendering on calendar
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
selectable: false,
selectHelper: false,
editable: false,
events: // on-click next-previous button load events using Ajax
// post date using Ajax, then query to fetch all events and return data
});
JSON not working in my case
From the FullCalendar Online Documentation
FullCalendar will call this function whenever it needs new event data.
This is triggered when the user clicks prev/next or switches views.
This function will be given start and end parameters, which are
Moments denoting the range the calendar needs events for.
timezone is a string/boolean describing the calendar's current
timezone. It is the exact value of the timezone option.
It will also be given callback, a function that must be called when
the custom event function has generated its events. It is the event
function's responsibility to make sure callback is being called with
an array of Event Objects.
Here is an example showing how to use an event function to fetch
events from a hypothetical XML feed:
$('#calendar').fullCalendar({
events: function(start, end, timezone, callback) {
$.ajax({
url: 'myxmlfeed.php',
dataType: 'xml',
data: {
// our hypothetical feed requires UNIX timestamps
start: start.unix(),
end: end.unix()
},
success: function(doc) {
var events = [];
$(doc).find('event').each(function() {
events.push({
title: $(this).attr('title'),
start: $(this).attr('start') // will be parsed
});
});
callback(events);
}
});
}
});
Source
I made some little changes:
$('#calendar').fullCalendar({
events: function(start, end, timezone, callback) {
jQuery.ajax({
url: 'schedule.php/load',
type: 'POST',
dataType: 'json',
data: {
start: start.format(),
end: end.format()
},
success: function(doc) {
var events = [];
if(!!doc.result){
$.map( doc.result, function( r ) {
events.push({
id: r.id,
title: r.title,
start: r.date_start,
end: r.date_end
});
});
}
callback(events);
}
});
}
});
Notes: start and end MUST be ISO 8601. Another change was the use of format instead of unix (this made easier for me to deal with the code-behind)
There is a built in option avaliable
var calendar = new FullCalendar.Calendar(calendarEl, {
events: '/myfeed.php'
})
more details https://fullcalendar.io/docs/events-json-feed
This is perfect way to load data properly.
// if you want to empty events already in calendar.
$('#calendar').fullCalendar('destroy');
$.ajax({
url: 'ABC.com/Calendar/GetAllCalendar/',
type: 'POST',
async: false,
data: { Id: 1 },
success: function (data) {
obj = JSON.stringify(data);
},
error: function (xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
}
});
/* initialize the external events
-----------------------------------------------------------------*/
$('#external-events div.external-event').each(function () {
// create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/)
// it doesn't need to have a start or end
var eventObject = {
title: $.trim($(this).text()) // use the element's text as the event title
};
// store the Event Object in the DOM element so we can get to it later
$(this).data('eventObject', eventObject);
// make the event draggable using jQuery UI
$(this).draggable({
zIndex: 999,
revert: true, // will cause the event to go back to its
revertDuration: 0 // original position after the drag
});
});
/* initialize the calendar
-----------------------------------------------------------------*/
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var calendar = $('#calendar').fullCalendar({
//isRTL: true,
buttonHtml: {
prev: '<i class="ace-icon fa fa-chevron-left"></i>',
next: '<i class="ace-icon fa fa-chevron-right"></i>'
},
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
//obj that we get json result from ajax
events: JSON.parse(obj)
,
editable: true,
selectable: true
});
fullCalendar already uses ajax, so you don't have to type it. When I was starting to implement fullCalendar I used the solution of the most voted answer here:
https://stackoverflow.com/a/25404081/3927450
but then I could prove, that fullCalendar is in charge of making the ajax call the times the view changes without you having to do anything. I find this plugin very useful, although the documentation did not seem very clear to me.
So this code:
events: function(start, end, timezone, callback) {
jQuery.ajax({
url: 'schedule.php/load',
type: 'POST',
dataType: 'json',
is exactly this:
events: schedule.php/load,
you only have to provide the url. Off course you have to deal with a proper JSON response from the server. Or if you need more params you can do it like this:
events: {
url: '/myfeed.php',
method: 'POST',
extraParams: {
custom_param1: 'something',
custom_param2: 'somethingelse'
},
failure: function() {
alert('there was an error while fetching events!');
},
color: 'yellow', // a non-ajax option
textColor: 'black' // a non-ajax option
}
var events= '';
$.ajax({
url: '/eventoscalendar',
dataType: 'json',
type: 'GET',
success: function(data) {
events= JSON.stringify(data);
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay'
},
editable: true,
displayEventTime: true,
selectable: true,
droppable: false,
events: JSON.parse(events)
});
}
});
y en /eventoscalendar
public function eventoscalendar()
{
$events[]= [
"title" =>'Meeting',
"start"=> date('Y-m-d'),
"allDay"=> false,
"url"=> 'http://google.com/'
];
return JsonResponse::create($events, 200, array('Content-Type'=>'application/json; charset=utf-8' ));
}

Needing example to load jqplot with multiple series, date-based data from json file

Been searching and cannot find exactly what I am looking for. Need to load multiple series into one jqplot, with each series coming from its own data file.
The example here http://www.jqplot.com/tests/data-renderers.php does show how to load a series from a file, but when I convert file to have date data, then it stops working, probably just a formatting issue, but cannot solve. What am I doing wrong?
Here is the data in the txt file:
[["7/11/2011 04:00:00am",85.0],["7/12/2011 04:00:00AM",87.4],["7/13/2011 04:00:00AM",90.0]]
Here is the code:
<script class="code" type="text/javascript">$(document).ready(function(){
var line = [ ];
var ajaxDataRenderer = function(url, plot) {
var ret = null;
$.ajax({
// have to use synchronous here, else returns before data is fetched
async: false,
url: url,
dataType:'json',
success: function(data) {
ret = data;
}
});
return ret;
};
var jsonurl = "./jsondata1.txt";
plo12 = $.jqplot('chart2', jsonurl,{
title: 'AJAX JSON Data Renderer',
dataRenderer: ajaxDataRenderer,
axes: {
xaxis: {
renderer:$.jqplot.DateAxisRenderer,
tickInterval: '1 day',
tickOptions:{formatString:'%y/%m/%d'}
}
}
});
});</script>
You could use the dataRendererOptions parameter to declare possible files, like this:
plo12 = $.jqplot('chart2', jsonurl,{
title: 'AJAX JSON Data Renderer',
dataRenderer: ajaxDataRenderer,
dataRendererOptions: {file1:'name_of_file_1', file2:'name_of_file2'}
axes: {
xaxis: {
Next use for-each to iterate trough the dataRendererOptions - Object:
var ajaxDataRenderer = function(url, plot,op) {
var ret = null;
$.each(op,function(i,n) {
$.ajax({
// have to use synchronous here, else returns before data is fetched
async: false,
url: url+'/'+i,
dataType:'json',
success: function(data) {
ret[]= data;
}
}); //end ajax
});//end each
return ret;
}
This code is not testet, but the idea behind could fit your needs.

Resources