FullCalendar.js not showing events in IE 10 and FF 21.0 - php

I created a calendar with FullCalendar.js and it's working fine on Chrome (v.27) but not working on IE 10 e FF 21.0. Here the code that renders the events:
<?php
$user_selected = (isset($_GET['id'])) ? $_GET['id'] : $_SESSION[$pre_ssn.'userid'];
// [...]
$get_dati_calendar = mysql_query("SELECT * FROM calendario_fonderia WHERE user_id = $user_selected ");
$eventi = '[';
while ($calendar = mysql_fetch_array($get_dati_calendar)) {
$coloring = ($calendar['eur_gr'] != '') ? ", className: 'fc-event-done'" : '';
$dati_cal = ($calendar['eur_gr'] != '') ? $calendar['grammi'].' gr.\n'.$calendar['eur_gr'].' €/gr' : $calendar['grammi'].' gr.' ;
$eventi .= "{ title: '".$dati_cal."', start: new Date('".$calendar['data']."'), allDay: true ".$coloring." },";
}
echo ($eventi != '[') ? substr($eventi, 0, -1)."]\n" : "[]\n";
?>
And this is the full code (with at the end the php renderer):
jQuery(document).ready(function() {
//datepicker
jQuery('#datepicker').datepicker();
// tabbed widget
jQuery('.tabbedwidget').tabs();
function shortAjax(file, mode, dati){
var datiEx = jQuery.ajax({
type: "POST",
url: file+".php",
data: "mode="+mode+"&"+dati,
async: false}).responseText;
return datiEx;
}
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var eventi_gg = Array();
var calendar = jQuery('#calendar').fullCalendar({
firstDay: 1, // Start with Monday
header: {
left: 'prev,next today',
center: 'title',
right: false
},
buttonText: {
prev: '«',
next: '»',
prevYear: ' << ',
nextYear: ' >> ',
today: 'today'
},
monthNamesShort: [ "Gen", "Feb", "Mar", "Apr", "Mag", "Giu", "Lug", "Ago", "Sett", "Ott", "Nov", "Dic"],
monthNames: [ "Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"],
dayNames : ["Domenica", "Lunedì", "Martedì", "Mercoledì", "Giovedì", "Venerdì", "Sabato", "Domenica"],
dayNamesShort : ["Dom", "Lun", "Mar", "Mer", "Giov", "Ven", "Sab", "Dom"],
allDayText: "GIORNATA",
titleFormat:{month:"MMMM yyyy",week:"d [ yyyy]{ '—'d MMM[ MMM] yyyy}",day:"dddd d MMM yyyy"},
columnFormat:{month:"ddd",week:"dddd d/M",day:"dddd d MMMM"},
buttonText: {
prev: '«',
next: '»',
prevYear: ' << ',
nextYear: ' >> ',
today: 'oggi'
},
selectable: false,
editable: false,
loading: function(bool) {
if (bool) $('#loader_layer').show();
else $('#loader_layer').hide();
},
dayClick: function(start) {
jQuery(this).append("<div style='text-align:center; position:relative; top:50%;' id='load-calendar'><img src='images/loaders/loader10-1.gif' /></div>");
var oggi = date.getFullYear()+'-'+ ('0' + (date.getMonth()+1)).slice(-2)+'-'+('0' + date.getDate()).slice(-2);
data_click = jQuery.fullCalendar.formatDate(start, "yyyy-MM-dd HH:mm:ss");
data_click_short = jQuery.fullCalendar.formatDate(start, "yyyy-MM-dd");
giorno_click = jQuery.fullCalendar.formatDate(start, "dd/MM");
var numEventi = shortAjax("handler_fonderia", "check_event", "data="+data_click_short);
//console.log(data_click_short+'-'+oggi);
//&& data_click_short == oggi
if(numEventi == 0 ){
jQuery.alerts.dialogClass = 'alert-danger';
jQuery.alerts.okButton = 'Prosegui';
var deposito = shortAjax("handler_fonderia", "get_deposito", "id=");
jPrompt('Grammi:', '', 'Aggiunta Grammi al '+giorno_click, function(grammi) {
if(grammi){
grammi = parseFloat(grammi);
//jAlert(grammi+' - '+deposito);/*
if(grammi <= deposito){
jQuery.alerts.okButton = 'Confermo';
jQuery.alerts.cancelButton = 'No, Annulla';
jConfirm('Stai per inserire <b>'+grammi+'</b> grammi per il giorno <b>'+giorno_click+'</b>.<br>Questi dati non possono più essere modificati. Confermi?', 'CONFERMA GRAMMI', function(conferma){
if(conferma){
var creaEvento = shortAjax("handler_fonderia", "add_grammi", "grammi="+grammi+"&data="+data_click+"&day="+data_click_short);
if(creaEvento == "true"){
jQuery('#load-calendar').remove();
var resdeposito = parseFloat(jQuery('#depositoVal').val()-grammi);
var cumdeposito = parseFloat(jQuery('#depositoCum').val());
var totdeposito = parseFloat(cumdeposito+grammi);
jQuery('#totDeposito').val('Deposito: '+resdeposito.toFixed(1)+' gr.');
jQuery('#totVenduto').val('Venduto: '+totdeposito.toFixed(1)+' gr.');
calendar.fullCalendar('renderEvent', {
title: grammi + " gr.",
start: start
}, true);
}
}
});
}else{
jQuery('#load-calendar').remove();
jQuery.alerts.okButton = 'OK';
jAlert('I grammi che vuoi inserire sono superiori al deposito.<br>Richiedere un nuovo deposito o inserire una grammatura inferiore.', 'Errore');
}
}jQuery('#load-calendar').remove();
});
}else if(numEventi == 0 && data_click_short < oggi){
jQuery('#load-calendar').remove();
jQuery.jGrowl("E' possibile inserire i grammi solo nel giorno corrente.", {header: '<span style="color:red; font-size:12px;">Attenzione</span>', life:8000});
}
},
editable: false,
events:
<?php
$get_dati_calendar = mysql_query("SELECT * FROM calendario_fonderia WHERE user_id = $user_selected ");
$eventi = '[';
while ($calendar = mysql_fetch_array($get_dati_calendar)) {
$coloring = ($calendar['eur_gr'] != '') ? ", className: 'fc-event-done'" : '';
$dati_cal = ($calendar['eur_gr'] != '') ? $calendar['grammi'].' gr.\n'.$calendar['eur_gr'].' €/gr' : $calendar['grammi'].' gr.' ;
$eventi .= "{ title: '".$dati_cal."', start: new Date('".$calendar['data']."'), allDay: true ".$coloring." },";
}
echo ($eventi != '[') ? substr($eventi, 0, -1)."]\n" : "[]\n";
?>
});
function effectFadeIn() {
jQuery('#ptDeposito').fadeOut(500).fadeIn(500, effectFadeOut());
}
function effectFadeOut() {
jQuery('#ptDeposito').fadeIn(500).fadeOut(500, effectFadeIn());
}
<?= $effect_on ?>
});
Event gets written on the DB and everything works fine on that side.
Unfortunately I can't give you a link for this. I'll try to JSfiddle it.
EDIT
I tried to see if the problem was the PHP echoing so I tried writing directly the event in JS like this:
events: [{ title : 'A',
start : new Date('2013-07-09 00:00:00'),
allDay : true, className: 'fc-event-done' }]
And it doesn't work, therefore the issue must be something else...

Look firefox error console. $user_selected nis not defined, php sent warning and sql error and break json code. Remember add json headers. And remember:
events:[,className: 'fc-event-done' ...
Is not correct, you need objects not arrays:
events: {className:'foo', etc...
Make an array in while and show with join(',') for correct concatenation.
Try it:
events:
<?php
$user_selected = 1; // ???
$get_dati_calendar = mysql_query("SELECT * FROM calendario_fonderia WHERE user_id = $user_selected ");
$data = array();
while ($calendar = mysql_fetch_array($get_dati_calendar)) {
$data[] = "{
title : '".(($calendar['eur_gr']) ? $calendar['grammi'].' gr.\n'.$calendar['eur_gr'].' €/gr' : $calendar['grammi'].' gr.')."',
start : new Date('".$calendar['data']."'),
allDay : true
".($calendar['eur_gr'] ? ", className: 'fc-event-done'" : "")."
}";
}
echo implode(',' $data);
?>
}
Or change for an array:
echo '['.implode(',' $data).']';

I'v logged in FF console new Date('2013-07-09 00:00:00') and get this error Date {Invalid Date}. If you try convert your date to ISO 8601 format, something like this 2013-07-09T19:10:00-04:00, all should work fine.
UPD: why you try not return response in json format from server side?

Try to load data in this datetime format "yyyy-MM-dd HH:mm:ss" it helps me. I'm using FullCaneldar in ASP.Net MVC C# project...

Related

How auto refresh Fullcalendar using mysql database

I'm using fullcalendar library for calendar view,
<div id="calendar">
<?PHP
include("Calendar.php");
?>
</div>
i managed to connect my fullcalendar to sql db using source code I got from internet which is Calendar.php
$sql = "SELECT id, title, start, end, color FROM tbl_calendar ";
$req = $bdd->prepare($sql);
$req->execute();
$events = $req->fetchAll();
, but how can i auto refresh my calendar?. the following is my code
$('#calendar').fullCalendar({
header: {
left: 'prev,next ',
center: 'title',
right: 'today'
},
editable: true,
eventLimit: true, // allow "more" link when too many events
selectable: true,
selectHelper: true,
select: function(start, end) {
$('#ModalAdd #start').val(moment(start).format('YYYY-MM-DD HH:mm:ss'));
$('#ModalAdd #end').val(moment(end).format('YYYY-MM-DD HH:mm:ss'));
$('#ModalAdd').modal('show');
},
eventRender: function(event, element) {
element.bind('dblclick', function() {
$('#ModalEdit #id').val(event.id);
$('#ModalEdit #title').val(event.title);
$('#ModalEdit #color').val(event.color);
$('#ModalEdit').modal('show');
});
},
eventDrop: function(event, delta, revertFunc) { // si changement de position
edit(event);
},
eventResize: function(event,dayDelta,minuteDelta,revertFunc) { // si changement de longueur
edit(event);
},
events: [
<?php foreach($events as $event):
$start = explode(" ", $event['start']);
$end = explode(" ", $event['end']);
if($start[1] == '00:00:00'){
$start = $start[0];
}else{
$start = $event['start'];
}
if($end[1] == '00:00:00'){
$end = $end[0];
}else{
$end = $event['end'];
}
?>
{
id: '<?php echo $event['id']; ?>',
title: '<?php echo $event['title']; ?>',
start: '<?php echo $start; ?>',
end: '<?php echo $end; ?>',
color: '<?php echo $event['color']; ?>',
},
<?php endforeach; ?>
]
});
i tried to use several functions such as
`setInterval(function(){
$('#calendar').fullCalendar( 'removeEventSource', "Fetch.php" )
$('#calendar').fullCalendar( 'addEventSource', "Fetch.php" )
$("#calendar").fullCalendar( 'refetchEvents' )
}, 1000);`
but it doesn't refresh calendar but the calendar is keep blinking.
any solutions?

How to get expandable details using datatable with tabletools?

How to get expandable details on click, I want my table details like:
In the above image when I click on (+) sign it will give me more fields of table, I want that type of functionality in my datatable.
Here is my html code :
<div class="row">
<div class="col-md-12">
<!-- BEGIN EXAMPLE TABLE PORTLET-->
<div class="portlet box blue-hoki">
<div class="portlet-title">
<div class="caption">
<i class="fa fa-globe"></i>Prestart Hand Tools/Electric Power Tool Safety Checks
</div>
<div class="tools">
</div>
</div>
<div class="portlet-body">
<table class="table table-striped table-bordered table-hover" id="tblListing">
<thead>
<tr>
<th>Sr. No.</th>
<th>User</th>
<th>Model</th>
<th>Safety Inspection Due</th>
<th>MachineOwner</th>
<th>MachineType</th>
<th>FleetLicNum</th>
<th>YearOfMan</th>
<th>Manufactur</th>
<th>Image</th>
<th>Action</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
var cOptions = [];
cOptions.columnDefs = [{
data: "srNo",
targets: 0,
orderable: false,
width: 50
}, {
data: "user_id",
targets: 1,
width: 150
}, {
data: "Model",
targets: 2,
width: 200
}, {
data: "SafetyInspectionDue",
targets: 3,
width: 150
}, {
data: "MachineOwner",
targets: 4,
width: 50
}, {
data: "MachineType",
targets: 5,
width: 50
}, {
data: "FleetLicNum",
targets: 6,
width: 50
}, {
data: "YearOfMan",
targets: 7,
width: 50
}, {
data: "Manufactur",
targets: 8,
width: 50
}, {
data: "ToolImage",
targets: 9,
orderable: false,
className: "dt-center",
width: 50
}, {
data: "action",
targets: 10,
orderable: false,
className: "dt-center",
width: 150
}];
cOptions.order = [
[1, 'asc']
];
cOptions.mColumns = [1, 2, 3, 4, 5, 6, 7, 8];
cOptions.url = 'ajax/mytoolbox.php';
Custom.initListingTable(cOptions);
</script>
My ajax/mytoolbox.php File :
<?php
include '../application/application_top.php';
include ROOT . '/application/function.php';
include_once '../../classes/mytoolbox.class.php';
$response['status'] = '';
$response['errorMsg'] = '';
$action = get_data('action', '');
if ($action == 'getList') {
$request = $_REQUEST;
$start = $request["start"];
$length = $request["length"];
$order = $request["order"];
$orderby = "Model DESC";
$search = $request["search"]["value"];
if ($order[0]['column'] == 1) {
$orderby = "reg.reg_fname " . strtoupper($order[0]['dir']);
} elseif ($order[0]['column'] == 2) {
$orderby = "Model " . strtoupper($order[0]['dir']);
} elseif ($order[0]['column'] == 3) {
$orderby = "SafetyInspectionDue " . strtoupper($order[0]['dir']);
} elseif ($order[0]['column'] == 4) {
$orderby = "MachineOwner " . strtoupper($order[0]['dir']);
} elseif ($order[0]['column'] == 5) {
$orderby = "MachineType " . strtoupper($order[0]['dir']);
} elseif ($order[0]['column'] == 6) {
$orderby = "FleetLicNum " . strtoupper($order[0]['dir']);
} elseif ($order[0]['column'] == 7) {
$orderby = "YearOfMan " . strtoupper($order[0]['dir']);
} elseif ($order[0]['column'] == 8) {
$orderby = "Manufactur " . strtoupper($order[0]['dir']);
}
$tableData = array();
$mytoolbox = new Mytoolbox();
$mytoolbox->cquery = "SELECT SQL_CALC_FOUND_ROWS mytoolbox.*,CONCAT(reg.reg_fname,' ',reg.reg_lname) as name from safe_my_tool_box as mytoolbox LEFT JOIN safe_register as reg on mytoolbox.user_id = reg.reg_id WHERE mytoolbox.is_delete='0'";
if ($search != "") {
$mytoolbox->cquery .= " AND (CONCAT(reg.reg_fname,' ',reg.reg_lname) LIKE '%" . $search . "%' OR Model LIKE '%" . $search . "%' OR YearOfMan LIKE '%" . $search . "%' )";
}
$mytoolbox->cquery .= " ORDER BY " . $orderby;
if ($length != -1)
$mytoolbox->cquery .= " LIMIT " . $start . "," . $length;
$mytoolbox->action = "get";
$mytoolbox_res = $mytoolbox->process();
foreach ($mytoolbox_res['res'] as $mytoolbox_row_key => $mytoolbox_row) {
$tableData[$mytoolbox_row_key]['srNo'] = '';
$tableData[$mytoolbox_row_key]['user_id'] = $mytoolbox_row['name'];
$tableData[$mytoolbox_row_key]['Model'] = $mytoolbox_row['Model'];
$tableData[$mytoolbox_row_key]['SafetyInspectionDue'] = $mytoolbox_row['SafetyInspectionDue'];
$tableData[$mytoolbox_row_key]['MachineOwner'] = $mytoolbox_row['MachineOwner'];
$tableData[$mytoolbox_row_key]['MachineType'] = $mytoolbox_row['MachineType'];
$tableData[$mytoolbox_row_key]['FleetLicNum'] = $mytoolbox_row['FleetLicNum'];
$tableData[$mytoolbox_row_key]['YearOfMan'] = $mytoolbox_row['YearOfMan'];
$tableData[$mytoolbox_row_key]['Manufactur'] = $mytoolbox_row['Manufactur'];
$tableData[$mytoolbox_row_key]['ToolImage'] = "<a href='#ImageModal' data-id='" . $mytoolbox_row['safe_my_tool_id'] . "' data-toggle='modal' alt='view'>Image</a>";
$tableData[$mytoolbox_row_key]['action'] = "<a href='#displayModal' data-id='" . $mytoolbox_row['safe_my_tool_id'] . "' data-toggle='modal' alt='view'>Question</a>"
. " | <a href='#confirmModal' data-id='" . $mytoolbox_row['safe_my_tool_id'] . "' data-toggle='modal' alt='Remove'>Delete</a>";
}
$data['data'] = $tableData;
$mytoolbox2 = new Mytoolbox();
$mytoolbox2->cquery = "SELECT FOUND_ROWS() as total_filter";
$mytoolbox2->action = "get";
$mytoolbox2_res = $mytoolbox2->process();
$mytoolbox1 = new Mytoolbox();
$mytoolbox1->cquery = "SELECT COUNT(*) AS total_tool_box FROM safe_my_tool_box WHERE is_delete='0'";
$mytoolbox1->action = "get";
$mytoolbox1_res = $mytoolbox1->process();
$data['recordsTotal'] = $mytoolbox1_res['res'][0]['total_tool_box'];
$data['recordsFiltered'] = $mytoolbox2_res['res'][0]['total_filter'];
echo json_encode($data);
exit(0);
}
?>
My custom.js file is :
var Custom = function () {
// private functions & variables
var myFunc = function(text) {
alert(text);
};
var initListingTable = function (cOptions) {
var table = $('#tblListing');
/* Table tools samples: https://www.datatables.net/release-datatables/extras/TableTools/ */
/* Set tabletools buttons and button container */
$.extend(true, $.fn.DataTable.TableTools.classes, {
container : "btn-group tabletools-dropdown-on-portlet",
buttons : {
normal : "btn btn-sm default",
disabled : "btn btn-sm default disabled"
},
collection: {
container : "DTTT_dropdown dropdown-menu tabletools-dropdown-menu"
}
});
var oTable = table.dataTable({
serverSide : true,
processing : true,
// Internationalisation. For more info refer to http://datatables.net/manual/i18n
language : {
aria : {
sortAscending : ": activate to sort column ascending",
sortDescending: ": activate to sort column descending"
},
emptyTable : "No data available",
info : "Showing _START_ to _END_ of _TOTAL_ entries",
infoEmpty : "No entries found",
infoFiltered : "(filtered from _MAX_ total entries)",
lengthMenu : "Show _MENU_ entries",
search : "Search:",
zeroRecords : "No matching records found"
},
// Or you can use remote translation file
//language: {
// url: '//cdn.datatables.net/plug-ins/3cfcc339e89/i18n/Portuguese.json'
//},
searching : true,
order : cOptions.order,
lengthMenu : [
[25, 50, 100, -1],
[25, 50, 100, "All"] // change per page values here
],
// set the initial value
pageLength : 25,
dom : "<'row' <'col-md-12'T>><'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r><'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>", // horizobtal scrollable datatable
fnRowCallback: function(nRow, aData, iDisplayIndex){
var oSettings = oTable.fnSettings();
var index = oSettings._iDisplayStart + iDisplayIndex + 1;
$('td:eq(0)',nRow).html(index);
return nRow;
},
ajax : {
type : "POST",
url : cOptions.url,
data: ({
action : "getList"
}),
dataSrc: function ( json ) {
return json.data;
}
},
responsive: {
details: {
type: 'column'
}
},
columnDefs: cOptions.columnDefs,
// Uncomment below line("dom" parameter) to fix the dropdown overflow issue in the datatable cells. The default datatable layout
// setup uses scrollable div(table-scrollable) with overflow:auto to enable vertical scroll(see: assets/global/plugins/datatables/plugins/bootstrap/dataTables.bootstrap.js).
// So when dropdowns used the scrollable div should be removed.
//dom: "<'row' <'col-md-12'T>><'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r>t<'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>",
tableTools: {
sSwfPath : Metronic.getAssetsPath()+"global/plugins/datatables/extensions/TableTools/swf/copy_csv_xls_pdf.swf",
aButtons : [{
sExtends : "pdf",
sButtonText : "PDF",
mColumns : cOptions.mColumns
}, {
sExtends : "csv",
sButtonText : "CSV",
mColumns : cOptions.mColumns
}, {
sExtends : "xls",
sButtonText : "Excel",
mColumns : cOptions.mColumns
}, {
sExtends : "print",
sButtonText : "Print",
sInfo : 'Please press "CTR+P" to print or "ESC" to quit',
sMessage : "Generated by DataTables",
mColumns : cOptions.mColumns
}]
}
});
var tableWrapper = $('#tblListing_wrapper'); // datatable creates the table wrapper by adding with id {your_table_jd}_wrapper
tableWrapper.find('.dataTables_length select').select2({minimumResultsForSearch: Infinity}); // initialize select2 dropdown
};
var handleDatePickers = function () {
if ($().datepicker) {
$('.date-picker').datepicker({
rtl: Metronic.isRTL(),
autoclose: true
});
//$('body').removeClass("modal-open"); // fix bug when inline picker is used in modal
}
/* Workaround to restrict daterange past date select: http://stackoverflow.com/questions/11933173/how-to-restrict-the-selectable-date-ranges-in-bootstrap-datepicker */
};
var handleTimePickers = function () {
if (jQuery().timepicker) {
$('.timepicker-default').timepicker({
autoclose: true,
showSeconds: true,
minuteStep: 1
});
$('.timepicker-no-seconds').timepicker({
autoclose: true,
minuteStep: 5
});
$('.timepicker-24').timepicker({
autoclose: true,
minuteStep: 5,
showSeconds: false,
showMeridian: false
});
// handle input group button click
$('.timepicker').parent('.input-group').on('click', '.input-group-btn', function(e){
e.preventDefault();
$(this).parent('.input-group').find('.timepicker').timepicker('showWidget');
});
}
};
// public functions
return {
//main function
init: function () {
//initialize here something.
handleDatePickers();
handleTimePickers();
},
//some helper function
doSomeStuff: function () {
myFunc();
},
initListingTable: function(cOptions) {
initListingTable(cOptions);
},
handleDatePickers: function() {
handleDatePickers();
},
handleTimePickers: function() {
handleTimePickers();
}
};
}();
Datatable Listing view :
I want the fields Safety Inspection Due, MachineOwner, and MachineType in expandable details.

how to update variable dynamically of currency rate WITH php/json/ajax

I would like to know how to update variable dynamically of currency rate WITH php/AJAX/json that $CurrencyValue (the currency value from yahoo finance) will update only if the variable is different than it was before.
For example:
on 01/01/2016 10:00 USDINR gate was 67.454.
1/01/2016 10:01 USDINR gate was 67.104 (the variable $CurrencyValue be updated).
1/01/2016 10:02 gate of USDINR remains 67.104 (the variable $CurrencyValue not be updated).
1/01/2016 10:03 USDINR gate was 67.024 (so the variable $CurrencyValue be updated).
It is important the page will not refreshed, only the variable $CurrencyValue also if the variable changed I would like to get The exact date.
<?php
$from = 'USD'; $to = 'INR'; $url = 'http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s='. $from . $to .'=X'; $currencyValue = 0; $handle = fopen($url, 'r'); if ($handle) {
while (($data = fgetcsv($handle, 1024, ',', '"')) !== FALSE)
{
$currencyValue = $data[1];
}
fclose($handle);
} $date = date('l jS \of F Y h:i:s A');
?>
Value of 1 USDINR is <?php echo $currencyValue. ' - ' .$date; ?>
Thank you
EDIT
I have a code of euro-dollar exchange via YAHOO FINANCE works with PHP / AJAX. My question is how to integrate the data released chart works with CHARTS.JS
labels: ["2016-06-02 12:41:06", "2016-06-02 12:41:08"],
datasets: [{
label: "My Third dataset - No bezier",
data: [1.1200,1.1205],
lineTension: 0,
fill: false,
}]
{"rate":"1.1200","time":"2016-06-02 12:41:06"}
{"rate":"1.1205","time":"2016-06-02 12:41:08"}
{"rate":"1.1199","time":"2016-06-02 12:41:10"}
{"rate":"1.1199","time":"2016-06-02 12:41:12"}
The Code:
<script src="Chart.bundle.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<style>
canvas {
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
}
</style>
<?php
if(isset($_GET['fetchOnly'])){
$from = 'eur';
$to = 'usd';
$url = 'http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s='. $from . $to .'=X';
$response = array();
$handle = fopen($url, 'r');
if ($handle) {
while (($data = fgetcsv($handle, 1024, ',', '"')) !== FALSE)
{
$response['rate'] = $data[1];
$response['time'] = date("Y-m-d H:i:s");
}
fclose($handle);
}
echo json_encode($response);
die();
}
?>
<div id="responseText"></div>
<script>
// run the function, it will re-run itself
fetchRate();
function fetchRate() {
// create the new AJAX Object
xmlhttp = new XMLHttpRequest();
// this handles the request
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
// if the request came back successfully
if(xmlhttp.status == 200){
// write the response to a div
div = document.getElementById("responseText")
div.innerHTML = div.innerHTML + '<br />'+ xmlhttp.responseText;
}else{
// if the request had an error
div.innerHTML = div.innerHTML + '<br />Error fetching rates error code : '+xmlhttp.status;
}
// rerun this function to fetch updates
setTimeout(fetchRate,1000);
}
};
// open the AJAX Object
xmlhttp.open("GET", "<?= basename(__FILE__) ?>?fetchOnly", true);
// send the AJAX request
xmlhttp.send();
}
</script>
<div style="width:100%;">
<canvas id="canvas"></canvas>
</div>
<script>
var MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var randomScalingFactor = function() {
return Math.round(Math.random() * 100 * (Math.random() > 0.5 ? -1 : 1));
};
var randomColorFactor = function() {
return Math.round(Math.random() * 255);
};
var randomColor = function(opacity) {
return 'rgba(' + randomColorFactor() + ',' + randomColorFactor() + ',' + randomColorFactor() + ',' + (opacity || '.3') + ')';
};
var config = {
type: 'line',
data: {
labels: ["2016-06-02 12:36:05", "2016-06-02 12:37:05"],
datasets: [{
label: "My Third dataset - No bezier",
data: [1,2],
lineTension: 0,
fill: false,
}]
},
options: {
responsive: true,
legend: {
position: 'bottom',
},
hover: {
mode: 'label'
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Month'
}
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Value'
}
}]
},
title: {
display: true,
text: 'Chart.js Line Chart - Legend'
}
}
};
$.each(config.data.datasets, function(i, dataset) {
var background = randomColor(0.5);
dataset.borderColor = background;
dataset.backgroundColor = background;
dataset.pointBorderColor = background;
dataset.pointBackgroundColor = background;
dataset.pointBorderWidth = 1;
});
window.onload = function() {
var ctx = document.getElementById("canvas").getContext("2d");
window.myLine = new Chart(ctx, config);
};
$('#randomizeData').click(function() {
$.each(config.data.datasets, function(i, dataset) {
dataset.data = dataset.data.map(function() {
return randomScalingFactor();
});
});
window.myLine.update();
});
$('#addDataset').click(function() {
var background = randomColor(0.5);
var newDataset = {
label: 'Dataset ' + config.data.datasets.length,
borderColor: background,
backgroundColor: background,
pointBorderColor: background,
pointBackgroundColor: background,
pointBorderWidth: 1,
fill: false,
data: [],
};
for (var index = 0; index < config.data.labels.length; ++index) {
newDataset.data.push(randomScalingFactor());
}
config.data.datasets.push(newDataset);
window.myLine.update();
});
$('#addData').click(function() {
if (config.data.datasets.length > 0) {
var month = MONTHS[config.data.labels.length % MONTHS.length];
config.data.labels.push(month);
$.each(config.data.datasets, function(i, dataset) {
dataset.data.push(randomScalingFactor());
});
window.myLine.update();
}
});
$('#removeDataset').click(function() {
config.data.datasets.splice(0, 1);
window.myLine.update();
});
$('#removeData').click(function() {
config.data.labels.splice(-1, 1); // remove the label first
config.data.datasets.forEach(function(dataset, datasetIndex) {
dataset.data.pop();
});
window.myLine.update();
});
</script>
Thank you.
<?php
if(isset($_GET['fetchOnly'])){
$from = 'USD';
$to = 'INR';
$url = 'http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s='. $from . $to .'=X';
$response = array();
$handle = fopen($url, 'r');
if ($handle) {
while (($data = fgetcsv($handle, 1024, ',', '"')) !== FALSE)
{
$response['rate'] = $data[1];
$response['date'] = $data[2];
$response['time'] = $data[3];
}
fclose($handle);
fclose($handle);
}
echo json_encode($response);
die();
}
?>
<div id="responseText"></div>
<script>
// run the function, it will re-run itself
fetchRate();
function fetchRate() {
// create the new AJAX Object
xmlhttp = new XMLHttpRequest();
// this handles the request
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
// if the request came back successfully
if(xmlhttp.status == 200){
// write the response to a div
div = document.getElementById("responseText")
div.innerHTML = div.innerHTML + '<br />'+ xmlhttp.responseText;
}else{
// if the request had an error
div.innerHTML = div.innerHTML + '<br />Error fetching rates error code : '+xmlhttp.status;
}
// rerun this function to fetch updates
setTimeout(fetchRate,3000);
}
};
// open the AJAX Object
xmlhttp.open("GET", "<?= basename(__FILE__) ?>?fetchOnly", true);
// send the AJAX request
xmlhttp.send();
}

Highcharts multiple series json from php

Hi guys i need help with Highcharts library, i have this array coming from php,
[{"name":"25% en cambio de aceite 76 lubricants","data":[["2015-09-07",1],["2015-09-23",2],["2015-09-24",3],["2015-09-30",3]]},{"name":"10% Descuento en filtro de aceite","data":[["2015-09-07",1],["2015-09-23",2],["2015-09-24",3],["2015-09-30",3],["2015-10-03",3],["2015-10-05",1],["2015-10-09",1],["2015-10-10",1]]}]
I need to show this as line chart dynamically, but have been unable to do it, i believe the error comes from the quotes in dates, needs to be in format [Date.UTC(2015, 2, 6), 3]
This is my php function that returns the json data
public function actionTransactionsRedeemed() {
// Transacciones Totales redimidas por merchant
$sql = "SELECT DISTINCT `transaction`.idPromotion, promotion.`name` FROM `transaction` INNER JOIN promotion ON `transaction`.idPromotion = promotion.idPromotion WHERE `transaction`.idMerchant = 2 AND `transaction`.idPromotion IS NOT NULL";
$idPromotion = Yii::app()->db->createCommand($sql)->queryAll();
$idPromotions = array();
$tempArray = array();
$result = array();
$i = 1;
$rs = array();
foreach($idPromotion as $i){
//process each item here
$id = $i["idPromotion"];
$tempArray['name'] = $i["name"];
$sql = "SELECT count(*) AS count, DATE(`transaction`.date) AS `date` FROM `transaction` WHERE `transaction`.idMerchant = 2 AND `transaction`.idPromotion = $id GROUP BY DATE(`transaction`.date)";
$transactionsRedeemed = Yii::app()->db->createCommand($sql)->queryAll();
foreach($transactionsRedeemed as $item2){
$rs[0] = $item2['date'];
$rs[1] = $item2['count'];
$tempArray['data'][] = $rs;
$rs = array();
}
$i++;
array_push($result, $tempArray);
}
//$result = json_encode($result, JSON_NUMERIC_CHECK);
//echo json_decode($result);
print json_encode($result, JSON_NUMERIC_CHECK);
}
And this is the Jquery that builds the chart
$(document).ready(function() {
var options = {
chart: {
type: 'spline',
renderTo: 'chart-merchant-day',
defaultSeriesType: 'spline',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'Total de promociones redimidas',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: { // don't display the dummy year
month: '%e. %b',
year: '%b'
},
labels: {
align: 'center',
x: -3,
y: 20,
formatter: function() {
return Highcharts.dateFormat('%l%p', this.value);
}
}
},
yAxis: {
title: {
text: 'Transacciones'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return Highcharts.dateFormat('%l%p', this.x-(24000*3600)) +'-'+ Highcharts.dateFormat('%l%p', this.x) +': <b>'+ this.y + '</b>';
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: [{
name: 'Count'
}],
credits: false
}
// Load data asynchronously using jQuery. On success, add the data
// to the options and initiate the chart.
jQuery.get('?r=/transactions/transactionsRedeemed', null, function(tsv) {
var lines = [];
traffic = [];
var data = $.parseJSON(tsv);
var x = 0;
//console.log(tsv);
$.each(data, function(i, item) {
//alert(item);
//console.log(item);
$.each(item, function(y, item2) {
if(y == "data"){
//console.log(item2);
try {
tsv = item2;
// split the data return into lines and parse them
tsv = tsv.split(/\n/g);
jQuery.each(tsv, function(i, line) {
line = line.split(/\t/);
options.series[x].data.push([Date.parse(line[0]),line[1]]);
/*date = Date.parse(line[0] +' UTC');
traffic.push([
date,
parseInt(line[1].replace(',', ''), 10)
]);*/
});
} catch (e) { }
options.series[x].data = traffic;
} else if(y == "name"){
options.series[x].name = item2;
}
});
x++;
});
chart = new Highcharts.Chart(options);
//console.log(tsv.replace(/\"/g, ""));
//tsv = tsv.replace(/\"/g, "");
});
});
Any help will be greatly appreciated, im so exhausted at this point.
The function is actually simpler,
jQuery.get('?r=/transactions/transactionsRedeemed', null, function(tsv) {
var data = $.parseJSON(tsv);
$.each(data, function (i, item) {
options.series.push({
name: item['name'],
data: []
});
$.each(item['data'], function (j, dataitem) {
var dataitemvalue = null;
try {
dataitemvalue = [Date.parse(dataitem[0]), dataitem[1]];
} catch (e) {}
options.series[i].data.push(dataitemvalue);
});
});
chart = new Highcharts.Chart(options);
});
JSFiddle demo

I need to add day to this js?

This is my js/php displaying function:
<script type="text/javascript">
$.fn.cycle.defaults.speed = 900;
$.fn.cycle.defaults.timeout = 5000;
$(function()
{
$('#demos pre code').each(function()
{
eval($(this).text());
});
$('#demos2 pre code').each(function()
{
eval($(this).text());
});
});
$(function($) {
var pstOptions = {
timeNotation: '12h',
am_pm: true,
utc: true,
utc_offset: <%SETTING_TIMEOFFSET%>,
fontFamily: 'Verdana, Times New Roman',
fontSize: '11px',
foreground: 'white',
background: 'black'
}
$('.jclockPST').jclock(pstOptions);
});
</script>
and this is my full js script:
/*
* jQuery jclock - Clock plugin - v 0.2.1
* http://plugins.jquery.com/project/jclock
*
* Copyright (c) 2007-2008 Doug Sparling <http://www.dougsparling.com>
* Licensed under the MIT License:
* http://www.opensource.org/licenses/mit-license.php
*/
(function($) {
$.fn.jclock = function(options) {
var version = '0.2.1';
// options
var opts = $.extend({}, $.fn.jclock.defaults, options);
return this.each(function() {
$this = $(this);
$this.timerID = null;
$this.running = false;
$.fn.jclock.getServerOffset($this);
var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
$this.timeNotation = o.timeNotation;
$this.am_pm = o.am_pm;
$this.utc = o.utc;
$this.utc_offset = o.utc_offset;
$this.css({
fontFamily: o.fontFamily,
fontSize: o.fontSize,
backgroundColor: o.background,
color: o.foreground
});
$.fn.jclock.startClock($this);
});
};
$.fn.jclock.getServerOffset = function(el) {
//Want to make a synchronous call to the server to get the server time.
$.ajax({
url: "Time.php",
async: false,
context: el,
success: function(result) {
var serverDate = new Date(+(result) * 1000); //Convert the seconds to a number, and multiple by 1000 to get milliseconds.
var clientDate = new Date();
$this = $(this.context[0]);
$this.serverOffset = clientDate - serverDate; //Set the offset between server and client.
}
});
};
$.fn.jclock.startClock = function(el) {
$.fn.jclock.stopClock(el);
$.fn.jclock.displayTime(el);
};
$.fn.jclock.stopClock = function(el) {
if(el.running) {
clearTimeout(el.timerID);
}
el.running = false;
};
$.fn.jclock.displayTime = function(el) {
var time = $.fn.jclock.getTime(el);
el.html(time);
el.timerID = setTimeout(function(){$.fn.jclock.displayTime(el)},1000);
};
$.fn.jclock.getTime = function(el) {
var now = new Date(new Date().getTime() - el.serverOffset); //Apply the server offset.
var hours, minutes, seconds;
if(el.utc == true) {
if(el.utc_offset != 0) {
now.setUTCHours(now.getUTCHours()+el.utc_offset);
}
hours = now.getUTCHours();
minutes = now.getUTCMinutes();
seconds = now.getUTCSeconds();
} else {
hours = now.getHours();
minutes = now.getMinutes();
seconds = now.getSeconds();
}
var am_pm_text = '';
(hours >= 12) ? am_pm_text = " P.M." : am_pm_text = " A.M.";
if (el.timeNotation == '12h') {
hours = ((hours > 12) ? hours - 12 : hours);
} else {
hours = ((hours < 10) ? "0" : "") + hours;
}
minutes = ((minutes < 10) ? "0" : "") + minutes;
seconds = ((seconds < 10) ? "0" : "") + seconds;
var timeNow = hours + ":" + minutes + ":" + seconds;
if ( (el.timeNotation == '12h') && (el.am_pm == true) ) {
timeNow += am_pm_text;
}
return timeNow;
};
// plugin defaults
$.fn.jclock.defaults = {
timeNotation: '24h',
am_pm: false,
utc: false,
fontFamily: '',
fontSize: '',
foreground: '',
background: '',
utc_offset: 0
};
})(jQuery);
How to add Date on it, so it will display Monday, Tuesday and etc ? My current time is obtained via time.php via
echo time();
I hope someone will be able to help me out since I dont want to break something.
It's a big thanks in advance.
Javascript doesn't have a nice way of printing out the day name like PHP does, you have to code the names manually, starting with Sunday:
var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var date = new Date();
console.log(days[date.getDay()]); // Wednesday
More info here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getDay
EDIT: If you want to do this all with the jclock plugin, you can use the format parameter to specify the output format. The format symbol for the day name is %A. For an example using the format option, see: https://github.com/dsparling/jclock/blob/master/examples/clock2.html

Categories