Home > database >  How to display data from database in full calendar using php
How to display data from database in full calendar using php

Time:10-12

I want to show data in full calender api from database. I am giving data in array but in console displaying undefined data and not showing data in calender. it is a schedule calender i want to show the schedule data in calendar.the data doesn't appear in the calendar, but it does appear in console.log.

    function get_schecdule($id2)
    {
    
        $sql = "SELECT * FROM `schedule` where `id`='0' or `id`='$id2'";
        $result = myQuery($sql) or die("Query Failed.");
        $row = myFetchArray($result);
    
        $schedule_list = $row['schedule_list'];
        $events = json_decode($schedule_list, true);
        $arr = [];
        foreach ($events as $event) {
            $type = $event['type'];
            $id1 = $event['id'];
            if ($type === 'asset') {
    
                $sql_assets = "SELECT * FROM `assets` WHERE `assets_id`='$id1'";
                $result_assets = myQuery($sql_assets);
                $row_assets = myFetchArray($result_assets);
                $name = $row_assets['name'];
            } elseif ($type === 'playlist') {
    
                $sql_playlists = "SELECT * FROM `playlist` WHERE `id`='$id1'";
                $result_playlists = myQuery($sql_playlists);
                $row_playlists = myFetchArray($result_playlists);
                $name = $row_playlists['playlist_name'];
            }
            $start = str_replace(' ', 'T', $event['start_datetime']);
            $end = str_replace(' ', 'T', $event['end_datetime']);
    
            $r = '
            {
                 "title": "' . $name . '",
                 "start": "' . $start . '",
                 "end": "' . $end . '"
             }
            ';
            array_push($arr, $r);
        }
    
        return json_encode($arr);
    }

 

    window.addEventListener('load', function() {
        calendar.destroy()
        start_load()
        let searchParams = new URLSearchParams(window.location.search);
        let id = searchParams.get('edit')
        $.ajax({
          url: 'get_schecdule.php',
          method: 'POST',
          data: {
            id: id
          },
          success: function(resp) {
            if (resp) {
              resp = JSON.parse(resp)
              var evt = [];
              if (resp.length > 0) {
                Object.keys(resp).map(k => {
                  var obj = {};
                  obj['title'] = resp[k].title
                  obj['start'] = resp[k].start
                  obj['end'] = resp[k].end;
    
                  evt.push(obj)
                })
                console.log(evt)
    
              }
              calendar = new FullCalendar.Calendar(calendarEl, {
                headerToolbar: {
                  left: 'prev,next today',
                  center: 'title',
                  right: 'dayGridMonth,timeGridWeek,timeGridDay,listMonth'
                },
                initialDate: '<?php echo date('Y-m-d') ?>',
                weekNumbers: true,
                navLinks: true,
                editable: false,
                selectable: true,
                nowIndicator: true,
                dayMaxEvents: true,
                select: function(info) {
                  var text = info.startStr.replace("T", " ");
                  var text2 = info.endStr.replace("T", " ");
                  document.getElementById("start-date").value = text.replace(" 05:00", " ");
                  document.getElementById("end-date").value = text2.replace(" 05:00", " ");
                  $('#exampleModal1').modal('show');
                },
                events: evt,
                eventClick: function(e, el) {
                  var data = e.event.extendedProps;
                  alert(data.data_id);
                  uni_modal('View Schedule Details', 'view_schedule.php?id='   data.data_id, 'mid-large')
    
                }
              });
            }
    


  [1]: https://i.stack.imgur.com/QVqqw.jpg

CodePudding user response:

Your variable $r is a string, which appears to try and generate JSON-formatted data. You are putting this string into an array, and then JSON-encoding your array. The result of that is you end up double-encoding the bit which was already a string. FullCalendar can't then read the event data because it's buried in a double-encoded string.

Here's a simple demo of that problem occurring in isolation: https://3v4l.org/HLUEp

A golden rule here is: Don't ever build JSON by hand. You run the risk of this kind of accidental double-encoding, and also of introducing unexpected syntax errors because you don't correctly escape certain characters, or you simply make a typo or whatever. Always just build a PHP data structure containing the data you want to output, and then let the json_encode function handle the encoding of the entire thing once, at the end. This is more reliable, and also more flexible in the case where you might want to be able to manipulate the data in other ways in the meantime, or also output it in a different way.

Here's how you should populate $r:

$r = [
  "title" => $name,
  "start" => $start,
  "end" => $end
];
array_push($arr, $r);   

Working demo: https://3v4l.org/2rlOG


P.S. Since your data is (now) in the format required by fullCalendar, there should be no reason to have to transform it in the JavaScript code after the AJAX call completes. In your "success" callback I think you can replace all of this:

resp = JSON.parse(resp)
var evt = [];
if (resp.length > 0) {
  Object.keys(resp).map(k => {
    var obj = {};
    obj['title'] = resp[k].title
    obj['start'] = resp[k].start
    obj['end'] = resp[k].end;
  })
  console.log(evt)
}

with simply:

var evt = JSON.parse(resp);
  • Related