I am using Laravel Datatables. I am successfully in loading data from a MySQL database through a query.
The problem I have is to be able to query the table by month by sending a month number. I am not able to successfully send a parameter containing the month number to my ajax function on the back end.
I tried many variations but nothing worked.
I get "Undefined index: month"
Here are my code snippets:
Javascript ajax:
<script>
$(function() {
var month = "<?= $brandData['month'] ?>"; // contains a month number
$('#accounts').DataTable({
processing: true,
serverSide: true,
type: "POST",
ajax: '{!! url('brand_ajax') !!}',
data : {'month' : month },
columns: [
{ data: 'brand_name', name: 'brand_name' , className: 'text-xl-left'},
{ data: 'brand_volume', name: 'brand_volume', className: 'text-xl-right' },
{ data: 'brand_margin', name: 'brand_margin' , className: 'text-xl-right'},
{ data: 'brand_commission', name: 'brand_commission', className: 'text-xl-right' },
]
});
});
</script>
Here is my ajax function to return data
public function brand_ajax()
{
$month = $_POST["month"];
$brands = SaleInvoice::select(DB::raw('brands.name as brand_name,
avg(NULLIF(margin,0)) as brand_margin,
sum(commission) as brand_commission,
sum(amt_invoiced) as brand_volume
'))
->join('brands', 'brands.ext_id', '=', 'saleinvoices.brand_id')
->where('brands.is_active', '=', true)
// ->whereRaw('MONTH(saleinvoices.invoice_date) = ?', (11))
->whereRaw('MONTH(saleinvoices.invoice_date) = ?', ($month))
->having('brand_volume', '>', 0)
->groupBy('brands.name')
->get();
return DataTables::of($brands)
->editColumn('brand_commission', function ($brand) {
return number_format($brand->brand_commission, 2);
})
->editColumn('brand_margin', function ($brand) {
return number_format($brand->brand_margin, 2);
})
->editColumn('brand_volume', function ($brand) {
return number_format($brand->brand_volume, 2);
})
->make(true);
}
I resolved it by myself. I just added the parameter to the URL string.
url('brand_ajax/' . $month)
Related
My event feed does only work when I hardcode the events in my EventController. Once I get them from database query the events are not displayed though the first event is the exact same I used in the hardcoded event.
Works (Calendar shows event):
public function eventFeed(Request $request)
{
$events = array(
[
"id" => 1,
"resourceId" => '1115',
"title" => 'Wartung Steuerung',
"start" => '2020-06-11 00:20:23',
"end" => '2020-06-28 21:21:30',
]
);
return json_encode($events);
}
From the calendar view I have a control Ajax call that fetches the same feed as FullCalendar. The received feed is
[{"id":1,"resourceId":"1115","title":"Wartung Steuerung","start":"2020-06-11 00:20:23","end":"2020-06-28 21:21:30"}]
Does not work (Calendar stays empty):
public function eventFeed(Request $request)
{
$start = Carbon::create($request->input('start'));
$end = Carbon::create($request->input('end'));
$events = DB::table('toolplanview')->select('id','resourceId','title','start','end')
->whereDate('start', '>=', $start)->whereDate('end', '<=', $end)->get();
return json_encode($events);
}
The feed from the DB query is:
[{"id":1,"resourceId":"1115","title":"Wartung Steuerung","start":"2020-06-11 00:20:23","end":"2020-06-28 21:21:30"},{"id":2,"resourceId":"1157","title":"Werkstatt","start":"2020-06-12 09:09:41","end":"2020-06-24 03:45:59"},{"id":3,"resourceId":"1136","title":"Neue Toranlage","start":"2020-06-10 20:29:44","end":"2020-06-23 04:26:38"},{"id":4,"resourceId":"1138","title":"Neue Toranlage","start":"2020-06-10 03:23:12","end":"2020-06-28 11:20:36"}]
I dont see why this feed would not work. My calendar:
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
schedulerLicenseKey: 'GPL-My-Project-Is-Open-Source',
locale: 'de',
plugins: [ 'interaction', 'resourceTimeline' ],
defaultView: 'resourceTimelineWeek',
editable: true,
titleFormat: { year: 'numeric', month: '2-digit', day: '2-digit' },
header: {
right: 'today prev,next'
},
slotLabelFormat: [
{ month: 'long', year: 'numeric' }, // top level of text
{ weekday: 'short', day: '2-digit' } // lower level of text
],
resources: 'http://localhost/matpro/public/resource-feed',
events: 'http://localhost/matpro/public/event-feed',
});
calendar.render();
});
I found the reason for this behaviour, the issue is the where clause of my DB query:
$events = DB::table('events')->select('id','resourceId','title','start','end')->get();
->whereDate('start', '>=', $start)->whereDate('end', '<=', $end)->get();
When calender e.g. displays a week from 01.06. to 08.06 and one of my (generally longer) events starts on 30.05. and ends on 05.06. this event won't be displayed due to the where clauses in my query. The example dates I picked for testing accidentally overlapped with the calender start or end and therefore did not show up.
Good day, i'm new to webix and codeigniter, i wanna ask if after getting the json from controller the format is like {End_date: "2019-07-31", value: "2019-07-31"} in console log, how to display on webix text?
function GetEndDate() {
return $.ajax('<?php echo base_url(); ?
>index.php/date/dateController/GetEndDate/' + Id);
}
webix.ready(function(){
$.when(GetEndDate()).done(function(EndDates){
EndDate = EndDates[0];
rendersformSection();
});
});
function rendersformSection(){
{view:'text', id:'Final_date', name:'Final_date', labelAlign:
'right',label:'Final Date', labelWidth:200,
suggest: {
filter: function (item, value) {
if (item.value.toString().toLowerCase().indexOf(value.toLowerCase()) >= 0)
return true;
return false;
},
body: {
data: EndDate,
datatype: "json",
template: function(obj){
return obj.End_date;
}
}
},
on: {
onBeforeShow: function () {
var texts = [];
EndDate.forEach(function (obj) {
texts.push(obj.value);
});
}
}
webix.ui(rendersformSection);
}
I expect when the page load. the final date will show the date get from the function GetEndDate().
I try to show some events from database in my fullCalendar but it doesn't work? My app is on Symfony 3. First I installed the ancarebeca/fullcalendar, I followed the installation step by step and my agenda is here! In my controller, I have a method to return a JSON array like this:
[{"1":{"id":1,"title":"test","start":"2017-08-01
18:00:00","end":"2017-08-01
20:00:00","allDay":true,"editable":true,"startEditable":true,"durationEditable":true,"overlap":true,"url":"","backgroundColor":"","textColor":"","className":"","rendering":"","constraint":1,"source":"","color":""},"2":{"id":2,"title":"test2","start":"2017-08-02
15:00:00","end":"2017-08-02
16:00:00","allDay":true,"editable":true,"startEditable":true,"durationEditable":true,"overlap":true,"url":"","backgroundColor":"","textColor":"","className":"","rendering":"","constraint":1,"source":"","color":""}}]
If you want look my method:
public function loadAction()
{
//dump($calendarService);die();
$em = $this->getDoctrine()->getManager();
$evenements = $em->getRepository('MALrmBundle:CalendarEvent')->findAll();
$calendarService = $this->get('ma_lrm_bundle.service.listener');
$events = array();
foreach ($evenements as $key => $evenement)
{
$events[$evenement->getId()]=$calendarService->loadData($evenement);
}
$response = new JsonResponse($events);
return $response->setData(array($events));
}
At the end, in my js file, i just call the url, like this:
events: 'http://localhost/ligne_rh/web/app_dev.php/admin/accueil/calendar',
...But i have no return in my calendar...
i also post my full Js file:
$(document).ready(function() {
$('#calendar').fullCalendar({
header: {
left: 'prev, next',
center: 'title',
right: 'month, agendaWeek, agendaDay'
},
timezone: ('Europe/London'),
businessHours: {
start: '09:00',
end: '17:30',
dow: [1, 2, 3, 4, 5]
},
allDaySlot: false,
defaultView: 'agendaWeek',
lazyFetching: true,
firstDay: 1,
selectable: true,
timeFormat: {
agenda: 'h:mmt',
'': 'h:mmt'
},
/*columnFormat: {
month: 'ddd',
week: 'ddd D/M',
day: 'dddd'
},*/
editable: true,
eventDurationEditable: true,
events: 'http://localhost/ligne_rh/web/app_dev.php/admin/accueil/calendar',
});
});
Please help me.
Your JSON is structured differently than it expects.
[{"1":{"title":"test","start":"2017-08-01 18:00"}}]
should be like
[{"title":"Title","test":"2017-08-01 18:00"}]
To fix, try changing
$events[$evenement->getId()]=$calendarService->loadData($evenement);
to
$events[]=$calendarService->loadData($evenement);
As an aside, I'm not familiar with Symphony but the return may be as easy as return $response;
since you already use $events in the $response = new JsonResponse($events);
or just return new JsonResponse($events);
Here is the relevant code:
VIEW PAGE:
<script type="text/javascript">
$(document).on("click", ".calendarview", function () {
var roomid = $(this).data('id');
//alert(roomid);exit;
$('#calendar_view').fullCalendar({
//events: [
// {
// title: 'All Day Event',
// start: roomid
// }
// ]
events: {
url: base_url+'home/calview',
dataType: 'json',
data: {roomid: roomid},
type: 'POST', // Send post data
error: function() {
alert('There was an error while fetching events.');
}
}
});
});
</script>
IN CONTROLLER
function calview()
{
$room_id =$this->input->post('roomid');
$events=$this->Home_model->find_room_availability($room_id);
$data_events = array();
foreach($events as $r) {
$data_events[] = array(
//"title" => $r->available,
"description" => 'available',
"start" => $r->dt);
}
echo json_encode(array("events" => $data_events));
exit();
}
MODEL:
function find_room_availability($room_id){
$result = $this->db->query("SELECT x.dt , r.room_cnt - COALESCE(SUM(`booking_cnt`),0) available FROM calendar_table x LEFT JOIN bookinglist y ON x.dt >= y.`date_from` AND x.dt < y.`date_to` LEFT JOIN rooms r ON r.id=$room_id WHERE x.dt BETWEEN now() - interval 3 month AND now() + interval 5 month GROUP BY dt ");
//echo $this->db->last_query();
//exit;
return $result->result();
}
Ajax response is like
[[{"title":"10","start":"2017-04-26"},{"title":"10","start":"2017-04-27"},
{"title":"10","start":"2017-04-28"},{"title":"10","start":"2017-04-29"},
{"title":"10","start":"2017-04-30"},{"title":"10","start":"2017-05-01"},
{"title":"10","start":"2017-05-02"},{"title":"10","start":"2017-05-03"},
{"title":"10","start":"2017-05-04"},{"title":"10","start":"2017-05-05"},
{"title":"10","start":"2017-05-06"},{"title":"10","start":"2017-05-07"},
{"title":"10","start":"2017-05-08"},{"title":"10","start":"2017-05-09"},
{"title":"10","start":"2017-05-10"},{"title":"10","start":"2017-05-11"},
{"title":"10","start":"2017-05-12"},{"title":"10","start":"2017-05-13"},
{"title":"10","start":"2017-05-14"},{"title":"10","start":"2017-05-15"},
{"title":"10","start":"2017-05-16"},{"title":"10","start":"2017-05-17"},}]]
can anyone please help me to find a solution
Your JSON is an array within an array, which fullCalendar cannot understand. It expects a single array of events.
This is the problem:
echo json_encode(array("events" => $data_events));
Since $data_events is already an array, there's no need to wrap it inside another one.
echo json_encode($data_events);
should be sufficient, and produce the format that fullCalendar is expecting.
N.B. There also appears to be a stray extra bracket at the end of your JSON sample: ,}]] but I'm assuming this is just a typo.
i'm having trouble trying to figure out how this is happening. i'm using Extjs and AJAX with JsonStore from my callback my page in ASP call the database and return some fields in this fields there is a Date and this date return the proper date ex.: "date_creat_post": "29\u002F04\u002F2011"...
Now once i look at my output from this in my page in a datagrid i'm getting the following:
04/05/2013 <----> the date it return in the callback is 04/05/2011
06/05/2012 <----> the date it return in the callback is 06/05/2010
07/04/2012 <----> the date it return in the callback is 07/04/2010
I looked all threw my code to see if they're is a place where i am adding 1 year to the date.
but can't find it. i have been trying now for at least 2 days to figure this out.
Here's my code:
Ext.onReady(function(){
Ext.QuickTips.init();
// for this demo configure local and remote urls for demo purposes
var url = {
local: '', // static data file
remote: '../myurl.asp'
};
// configure whether filter query is encoded or not (initially)
var encode = true;
// configure whether filtering is performed locally or remotely (initially)
var local = false;
var PostStore = new Ext.data.JsonStore({
// store configs
autoDestroy: true,
baseParams : {filter : '[{"type":"boolean","value":false,"field":"is_sent_post"}]'},// we start only with is_sent == false
url: url.remote,
remoteSort: false,
sortInfo: {
field: 'date_creat_post',
direction: 'DESC'
},
storeId: 'Post_Store',
// reader configs
idProperty: 'id_post',
root: 'Post',
totalProperty: 'totalcount',
fields: [{
name: 'id_post',
type: 'number'
}, {
name: 'name_post',
type: 'string'
}, {
name: 'date_creat_post',
type: 'date'//,
//dateFormat: 'Y-m-d H:i:s'
}, {
name: 'from_addr_post',
type: 'string'
}, {
name: 'sender_name_post',
type: 'string'
}, {
name: 'is_sent_post',
type: 'boolean'
}, {
name: 'date_sending_post',
type: 'date'//,
//dateFormat: 'Y-m-d H:i:s'
}, {
name: 'html_post',
type: 'string'
}, {
name: 'list_send_post',
type: 'number'
}],
writer: new Ext.data.JsonWriter({
writeAllFields: true
}),
autoSave: false,
batch: true
});
var filters = new Ext.ux.grid.GridFilters({
// encode and local configuration options defined previously for easier reuse
encode: encode, // json encode the filter query
local: local, // defaults to false (remote filtering)
filters: [{
type: 'numeric',
dataIndex: 'id_post'
}, {
type: 'string',
dataIndex: 'name_post'
}, {
type: 'date',
dataIndex: 'date_creat_post'
}, {
type: 'string',
dataIndex: 'from_addr_post'
}, {
type: 'string',
dataIndex: 'sender_name_post'
}, {
type: 'boolean',
dataIndex: 'is_sent_post'
}, {
type: 'date',
dataIndex: 'date_sending_post'
}, {
type: 'string',
dataIndex: 'html_post'
}, {
type: 'numeric',
dataIndex: 'list_send_post'
}]
});
// use a factory method to reduce code while demonstrating
// that the GridFilter plugin may be configured with or without
// the filter types (the filters may be specified on the column model
var createColModel = function (finish, start) {
var columns = [{
dataIndex: 'id_post',
hidden:true,
header: 'Id',
// instead of specifying filter config just specify filterable=true
// to use store's field's type property (if type property not
// explicitly specified in store config it will be 'auto' which
// GridFilters will assume to be 'StringFilter'
filterable: true
//,filter: {type: 'numeric'}
}, {
dataIndex: 'name_post',
header: 'Subject',
width: 150,
id: 'postname',
filter: {
type: 'string'
// specify disabled to disable the filter menu
//, disabled: true
}
}, {
dataIndex: 'date_creat_post',
header: 'Date Created',
renderer: Ext.util.Format.dateRenderer('d/m/Y'),
filter: {
type: 'date' // specify type here or in store fields config
}
}, {
dataIndex: 'from_addr_post',
header: 'From Address',
hidden:true,
id: 'fromaddress',
filter: {
type: 'string'
// specify disabled to disable the filter menu
//, disabled: true
}
}, {
dataIndex: 'sender_name_post',
header: 'Sender Name',
id: 'sendername',
filter: {
type: 'string'
// specify disabled to disable the filter menu
//, disabled: true
}
}, {
dataIndex: 'is_sent_post',
header: 'Status',
filter: {
type: 'boolean' // specify type here or in store fields config
},
renderer: function(value) {
var rtn = (value == 1) ? 'sent' : 'stand-by';
return rtn
}
}, {
dataIndex: 'date_sending_post',
header: 'Sending Date',
hidden:true,
//renderer: Ext.util.Format.dateRenderer('d/m/Y'),
filter: {
type: 'date' // specify type here or in store fields config
}
}, {
dataIndex: 'list_send_post',
header: 'Opticians list',
hidden:true,
id: 'optlist',
filter: {
type: 'number'
// specify disabled to disable the filter menu
//, disabled: true
}
}];
return new Ext.grid.ColumnModel({
columns: columns.slice(start || 0, finish),
defaults: {
sortable: true
}
});
};
/*
//======================contextMenu triggered by right click========================================
*/
var doRowCtxMenu = function ( thisGrid, rowIndex,cellIndex, evtObj )
{
//Ext.popup.msg('Done !', 'Right clicked !');
evtObj.stopEvent();
var sm = thisGrid.getSelectionModel();
var records = sm.getSelections(); // returns an array of Ext.data.Records
try
{
//var r = records[0]; // get the 1st Ext.data.Record of the list
thisGrid.rowCtxMenu = new Ext.menu.Menu({
items: [{
text : '<span style="color:red;">Delete Selected Email ?</span>',
handler : function () {
deletePost(records,thisGrid);
}
}]
});
thisGrid.rowCtxMenu.showAt(evtObj.getXY());
}
catch(err)
{
Ext.popup.msg('Warning !', 'You need to select a row first !');
}
};
/*
//======================END contextMenu triggered by right click========================================
//======================Delete Post Fonction =================================================
*/
function deletePost(records,thisGrid)
{
Ext.Msg.show({
title :'Warning !',
msg : 'You are about to delete 1 email !',
buttons : Ext.Msg.YESNOCANCEL,
fn : function(btn){
if (btn=='yes')
{
var store = thisGrid.getStore();
var s = thisGrid.getSelectionModel().getSelections();
for(var i = 0, r; r = s[i]; i++){
store.remove(r);
}
store.proxy.conn.url = '../myurl.asp';
store.save();
lastOptions = store.lastOptions;
/*Ext.apply(lastOptions.params, {
//myNewParam: true
});*/
store.load(lastOptions);
}
},
animEl : 'elId'
});
}
/*
//======================End delete Function========================================
*/
var Postgrid = new Ext.grid.GridPanel({
id:'post_grid',
border: false,
width: 462,
height:250,
store: PostStore,
colModel: createColModel(8),
loadMask: true,
viewConfig:{
emptyText:'No Post to display, change/clear your filters, refresh the grid or add a new Email!'
},
plugins: [filters],
sm: new Ext.grid.RowSelectionModel({
singleSelect: true,
listeners: {
rowselect: function(sm, row, rec) {
Ext.getCmp("post_form").getForm().loadRecord(rec);
//Ext.getCmp("htmlEdit").setValue("sdcdsdcdscsdc");
}
}
}),
//autoExpandColumn: 'company',
listeners: {
cellcontextmenu : doRowCtxMenu,
render: {
fn: function(){
PostStore.load({
params: {
start: 0,
limit: 50
}
});
}
}
},
bbar: new Ext.PagingToolbar({
store: PostStore,
pageSize: 50,
plugins: [filters]
})
});
// add some buttons to bottom toolbar just for demonstration purposes
Postgrid.getBottomToolbar().add([
'->',
{
text: 'Clear Filter Data',
handler: function () {
Postgrid.filters.clearFilters();
}
}
]);
var panelGrid = new Ext.Panel({
width : 462,
height : 250,
layout : 'fit',
renderTo: 'post-grid',
items: Postgrid
});
});
i will give my callback in firebug json:
{"totalcount":3, "Post": [{"id_post": 83,"name_post": "ghfgh","date_creat_post": "29\u002F04\u002F2011","from_addr_post": "fgh#sdf.com","sender_name_post": "gfh","is_sent_post": false,"date_sending_post": "29\u002F04\u002F2011","html_post": "<p>dfgdgdgd<\u002Fp>","list_send_post": null},{"id_post": 61,"name_post": "thomas test","date_creat_post": "28\u002F07\u002F2010","from_addr_post": "","sender_name_post": "","is_sent_post": false,"date_sending_post": "28\u002F07\u002F2010","html_post": "<p>test test test ets<\u002Fp>","list_send_post": null},{"id_post": 59,"name_post": "kevin test","date_creat_post": "29\u002F06\u002F2010","from_addr_post": "kevin#art-systems.net","sender_name_post": "kevin#art-systems.net","is_sent_post": false,"date_sending_post": "29\u002F06\u002F2010","html_post": "<p>jkljljoi ioijiio ijiojio oijio joijoi<\u002Fp>\u000A<p> <\u002Fp>\u000A<p><span style=\u0022background-color: #ffffff;\u0022>igiuihhuhi<\u002Fspan><\u002Fp>","list_send_post": null}]}
Thanks in advance i hope some on on the wicked web can help me....
cheers.
so after trying many solution giving to be i came to this has problem
finally the the date example after many attemps to format and inserting in my msSQL database
this problem is the problem : 13\09\2011 (d/m/Y) becomes this 09/01/2012 (d/m/Y) so for some reason the month 13 is being added to the month so say the 13 month doesn't exist so the date will go to 09/01/2012....
after looking again it's the format that doesn't seem ok so i changed it de (m/d/Y) and now im getting a sql error when i hit 13 day on my datefield in (extjs).
"The conversion of a varchar data type to a datetime data type resulted in an out-of-range value."
and on and on does anyone have any ideas now ????
Instead of using the built in Ext.util.Format.dateRenderer, you could try creating one of your own that parses the Date as desired.
ataIndex: 'date_creat_post',
header: 'Date Created',
renderer: daterenderer
And then a function for your daterenderer:
function dateRenderer(value, id, r) {
var myDate = r.data['date_creat_post'];
// do some things here to strip out the date and make it into a happy format
var d = new Date(myDate);
return d.format('d/m/Y');
}