I have a fullcalendar JS , in my events i would like to place my events data into the event field. My approach is by using php foreach and loop the data retrieved from DB and place into the event field. But i keep having this error saying ‘,’ is expected on the ‘{‘ section.
var allEvents = <?php echo json_encode($v_calendar_all_event_list); ?>;
console.log(allEvents);
events: [
<?php foreach ($v_calendar_all_event_list as $single_data): ?>
{
title : <?php echo $single_data['cal_title']?>,
start : <?php echo $single_data['cal_date']?>,
backgroundColor: '#f56954', //red
borderColor : '#f56954', //red
allDay : true
}
<?php endforeach;?>
],
The console logged data is as below
(3) [{…}, {…}, {…}]
0
:
{cal_id: '16', cal_date: '2023-01-03', cal_event: 'New Event 1 After Edit', cal_holiday: 'YES', cal_status: 'ACTIVE', …}
1
:
{cal_id: '17', cal_date: '2023-01-04', cal_event: 'New Event 1 After Edit', cal_holiday: 'YES', cal_status: 'ACTIVE', …}
2
:
{cal_id: '18', cal_date: '2023-01-05', cal_event: 'New Event 3 After Edit', cal_holiday: 'YES', cal_status: 'ACTIVE', …}
length
:
3
[[Prototype]]
:
Array(0)
Is there any better way to place php array data into this JS array field ?
>Solution :
-
initialize an empty array that will be used to store the events for
FullCalendar.$calendarEvents = []; -
Use a for loop to iterate through the $events array and add each event to the $calendarEvents array in the format required by FullCalendar.
for ($i = 0; $i < count($v_calendar_all_event_list); $i++) { $calendarEvents[] = [ 'title' => $v_calendar_all_event_list[$i]['title'], 'start' => $v_calendar_all_event_list[$i]['start'], 'end' => $v_calendar_all_event_list[$i]['end'], ]; } -
Finally, pass the $calendarEvents array to the FullCalendar JavaScript function and configure it to display the events.
<script> $(document).ready(function() { $('#calendar').fullCalendar({ events: <?php echo json_encode($calendarEvents); ?> }); }); </script>