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.
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.
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)
I'm working on a CodeIgniter (v3.1.9) project that displays graphs of data pulled from databases. I have 1 controller, 1 model, a main view, and each graph as subviews.
My model (currently only has 2 queries) that returns an array.
My controller is simple - an index function to pass the graph views to the main view and 2 functions for each graph. 1 that simply prints encoded json, and another that returns the graph view to the main view.
My views contain Javascript/jQuery that gets the JSON and creates/displays the graph (using c3js).
The Problem: One of the graphs displays fine and the other causes a 500 error. If I move the query causing the 500 above the other in my model.. both display fine and there is no error.
I found a similar question asked 2 years ago, but it remains unanswered.
What's causing this 500 error depending on the function order? How can I fix this?
Controller:
class ARDash extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model("ar_dash_model");
$this->load->database();
$this->load->helper('url');
}
public function index() {
$data['content'] = array();
array_push($data['content'], $this->displayReportsByClassification());
array_push($data['content'], $this->displayReportsByOccupation());
$this->load->view("Dash/AR/dash_view",$data);
}
function displayReportsByClassification() {
return $this->load->view("Dash/AR/by_classification.php", null, true);
}
function jsonReportsByClassification() {
$data = $this->ar_dash_model->dbGetReportsByClassification();
print json_encode($data);
}
function jsonReportsByOccupation() {
$data = $this->ar_dash_model->dbGetReportsByOccupation();
print json_encode($data);
}
function displayReportsByOccupation() {
$data = $this->load->view("Dash/AR/by_occupation.php", null, true);
return $data;
}
}
Model:
class ar_dash_model extends CI_Model {
function dbGetReportsByClassification() {
$results = array();
$sql = '
SELECT
Event_Class_ID,
EventClass_Name as name,
count(Event_ID) as count
FROM
Reports.tblEvent as incident
LEFT JOIN Reports.tblEventClass
ON Event_Class_ID = EventClass_ID
WHERE
incident.Event_Deleted is null AND
incident.Event_District_ID = '.$this->di.'
AND
Event_Occurred_Date_Time BETWEEN CAST("'.($this->dateRange["from"]).'" AS DATE) AND CAST("'.($this->dateRange["to"]).'" AS DATE)
GROUP BY
Event_Class_ID
ORDER BY count DESC
';
$query = $this->db->query($sql);
foreach ($query->result() as $row) {
if($row->name != '') {
$tmp = array();
$tmp['classification'] = $row->name;
$tmp['count'] = $row->count;
array_push($results, $tmp);
}
}
return $results;
}
}
/****************
* Moving this above the other function makes the 500 go away
*********/
function dbGetReportsByOccupation() {
$results = array();
$sql = '
SELECT
count(I.Event_ID) as count,
O.Occupation_Name as occupation
FROM
Reports.tblEvent AS I INNER JOIN Reports.tblARPerson AS P ON I.Event_ARPerson_ID = P.ARPerson_ID INNER JOIN mainDb.tblResource as R ON I.Event_Resource_ID = R.Resource_ID INNER JOIN mainDb.tblOccupation as O ON R.Resource_Primary_Occupation_ID = O.Occupation_ID
WHERE
I.Event_District_ID = '.$this->di.'
AND
I.Event_Deleted is null
AND
I.Event_Occurred_Date_Time BETWEEN CAST("'.($this->dateRange["from"]).'" AS DATE) AND CAST("'.($this->dateRange["to"]).'" AS DATE)
GROUP BY
O.Occupation_ID
ORDER BY
count DESC
';
$query = $this->db->query($sql);
foreach ($query->result() as $row) {
if($row->count != '') {
$tmp = array();
$tmp['occupation'] = $row->occupation;
$tmp['count'] = $row->count;
array_push($results, $tmp);
}
}
return $results;
}
Graph View (for query causing 500):
<div class="" id="occupationChart"></div>
<script type="text/javascript">
$.getJSON("<?php echo base_url();?>index.php/ARDash/jsonReportsByOccupation", function(data){
var chart = c3.generate({
bindto: '#occupationChart',
data: {
json: data,
keys: {
x: 'occupation',
value: ['Number of incidents']
},
type: 'bar',
empty: {
label: {
text: "No Data"
}
}
},
tooltip: {
show: true,
grouped: true
},
axis: {
rotated: true,
x: {
label: {
position: 'outer-center',
},
type: 'category',
categories: 'occupation'
},
y: {
tick: {
format: d3.format("d"),
outer: true,
count: 4
}
}
},
legend: {
show: false
}
});
});
</script>
I have an ajax function:
<script type="text/javascript">
$(document).ready(function() {
$('#{{ form.vars.name }}_documentlist').change(function() {
$.ajax({
type: "POST",
data: $("form").serialize(),
});
});
});
</script>
documentlist is a multiselect dropdowns and the selected "entries" are sent to my ActivationController:
/**
* #Route("/document/bulkdeactivate", name="documentBundle_document_bulkDeactivate")
* #Template()
*/
public function bulkDeactivateAction(Request $request) {
$em = $this->getDoctrine()->getManager();
$selected_documents[] = $request->getContent();
dump($selected_documents);
foreach($selected_documents as $document){
$params = json_decode($document, true);
dump($params);
}
$form = $this->createForm(DocumentDeactivationType::class);
$form->handleRequest($request);
if ($form->isSubmitted()) {
foreach($params as $document) {
$document->setActive(false);
$em->persist($document);
$em->flush();
$this->addFlash(
'success',
'The document has been deactivated!'
);
return $this->redirectToRoute('documentBundle_document_list');
}
}
return $this->render('DocumentBundle:Panels:ActivationPanel.html.twig', array(
'form' => $form->createView(),
));
}
But in my controller I'm doing something wrong. I'd like to persist the selected entries to my database and therefor decode them to objects.
Here are my thoughts to my code:
$selected_documents is an array because I can select several documents from my dropdown. I have the foreach loop for the decode because I can't decode an array and I didn't figure out how it would work better.
The first dump($selected_Documents) returns e.g.
array:1 [▼
0 => "search=&document_deactivation%5Bdocumentlist%5D%5B%5D=41"
]
the second dump($params) then returns null so apparently something with my decoding action is going wrong. I've read the documentation but can't really figure out what my mistake is.
Do you need any further information? would be happy about help!
I have two table "patient" and "booking" table, and there is a relationship "One to Many" between them, I want to set up a search form in an index_booking page where a user can type a patient_name on it and auto complete show all patient_name from patient table according to WHERE Condition.
This is Booking Model
class Booking extends Eloquent
{
public function patient()
{
return $this->belongsTo('App\Patient');
}
public function user()
{
return $this->belongsTo('App\User');
}
}
This is Patient Model
class Patient extends Eloquent
{
public function booking()
{
return $this->hasMany('App\Booking');
}
public function user()
{
return $this->belongsTo('App\User');
}
}
And i used this code in index page of booking
{!! Form::text('search_text', null, array('placeholder' => 'Search Text','class' => 'form-control','id'=>'search_text')) !!}
i used this code in Booking Controller to make autocomplete to show data
from patient table:
public function autoComplete(Request $request)
{
$patients = Patient::where('company_id', Auth::user()->company_id)
->where('patient_name', 'like', "&{$request->get('term')}&")
->get();
if ($patients->isEmpty()) {
return ['value' => 'No Result Found', 'id' => ''];
}
return $patients->map(function ($patient) {
return [
'id' => $patient->id,
'value' => $patient->patient_name,
];
});
}
And this is Route
Route::get('autocomplete',array('as'=>'autocomplete','uses'=>'BookingController#index'));
Route::get('searchajax',array('as'=>'searchajax','uses'=>'BookingController#autoComplete'));
Javascript code is
<script >
$(document).ready(function() {
src = "{{ route('searchajax') }}";
$("#search_text").autocomplete({
source: function(request, response) {
$.ajax({
url: src,
dataType: "json",
data: {
term : request.term
},
success: function(data) {
response(data);
}
});
},
minLength: 3,
});
});
</script>
when i type any patient name in search box i received a message No Result Found
this is the validator in booking controller :
public function store(Request $request)
{
//Validate Data
$this->validate($request, [
'patient_id'=> 'required|integer',
'booking_date'=> 'required|max:255',
'tybe'=> 'required',
'value'=>'required',
'doctor_name',
'patient_history',
'pharma',
'complaint',
'diagnosis',
'recomind',
'prescription',
'notes',
'document',
'by',
]);
//Insert Data to Database
$booking = new Booking;
$booking->patient_id = $request->patient_id;
$booking->booking_date = $request->booking_date;
$booking->tybe = $request->tybe;
$booking->value = $request->value;
$booking->doctor_name = $request->doctor_name;
$booking->patient_history = $request->patient_history;
$booking->pharma = $request->pharma;
$booking->complaint = $request->complaint;
$booking->diagnosis = $request->diagnosis;
$booking->recomind = $request->recomind;
$booking->prescription = $request->prescription;
$booking->notes = $request->notes;
$booking->document = $request->document;
$booking->by = $request->by;
$booking->save();
//to save multi selection Tags ,dont foget to add [] after -> tags in create post page then write this code here
//$post->tags()->sync($request->tags, false);
//Show Flash Message
Session::flash('success','تم حفظ البياانات');
//Redirect to another Page
return redirect()->route('booking.index');
}
SQL's syntax for matching with LIKE operator is:
WHERE `column` LIKE '%needle%'
Your code, on the other hand, produces the following:
WHERE `column` LIKE '&needle&'
Which is virtually the same as if you had typed:
WHERE `column` = '&needle&'
So what you need to do is to replace & with % in the following line:
->where('patient_name', 'like', "&{$request->get('term')}&")