How to fix failure parsing json using FullCalendar.js - javascript

I have question regarding on full calendar, I currently new for that, Why does my response shows. I currently getting the response from the url of my php file. I have module where I need to fetch all events on the calendar so I decided to use full calendar so right now I experience this error.
message: "Failure parsing JSON"
I will share to you guys my code that I made.
Front End:
<script>
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
plugins: [ 'interaction', 'dayGrid', 'timeGrid' ],
defaultView: 'dayGridMonth',
defaultDate: '2019-06-13',
header: {
left: 'prev,next ',
right: 'title',
},
events:'./Function/fetch_calendar_schedule.php',
eventColor: '#008B74',
eventTextColor: '#ffff'
});
calendar.render();
});
</script>
Back End:
<?php
require_once('../ConnectionString/require_db.php');
session_start();
$calendar_content = $db->prepare('SELECT event_name,event_start_date,event_end_date,link FROM tblevents')
or die($db->error);
$calendar_content->execute();
$calendar_content->bind_result($title,$start,$end,$link);
$result = array();
while($calendar_content->fetch()) {
//validate using user type where user redirect
$result[] = array('title'=>$title,'start'=>$start,'end'=>$end,'url'=>$link);
header('Content-type: application/json');
echo json_encode($result);
}
?>
Response Result:
[{"title":"<strong>42nd Annual Convention <\/strong>\r\nSMX MOA\r\nNovember 15, 2019\r\nScientific Chairperson: Dr. Panaligan\r\nCoordinators: Dr. Rowena Zabat","start":"0000-00-00 00:00:00","end":"0000-00-00 00:00:00","url":""}][{"title":"<strong>42nd Annual Convention <\/strong>\r\nSMX MOA\r\nNovember 15, 2019\r\nScientific Chairperson: Dr. Panaligan\r\nCoordinators: Dr. Rowena Zabat","start":"0000-00-00 00:00:00","end":"0000-00-00 00:00:00","url":""},{"title":"Download Registration Form (PDF)","start":"0000-00-00 00:00:00","end":"0000-00-00 00:00:00","url":"http:\/\/www.psmid.org\/forms\/pdf\/42nd-annual-registration.pdf"}][{"title":"<strong>42nd Annual Convention <\/strong>\r\nSMX MOA\r\nNovember 15, 2019\r\nScientific Chairperson: Dr. Panaligan\r\nCoordinators: Dr. Rowena Zabat","start":"0000-00-00 00:00:00","end":"0000-00-00 00:00:00","url":""},{"title":"Download Registration Form (PDF)","start":"0000-00-00 00:00:00","end":"0000-00-00 00:00:00","url":"http:\/\/www.psmid.org\/forms\/pdf\/42nd-annual-registration.pdf"},{"title":"Independence Day","start":"2019-06-12 00:00:00","end":"2019-06-12 00:00:00","url":""}]

To solved to problem, I put the json_encode result outside the loop:
<?php
require_once('../ConnectionString/require_db.php');
session_start();
$calendar_content = $db->prepare('SELECT event_name,event_start_date,event_end_date,link FROM tblevents')
or die($db->error);
$calendar_content->execute();
$calendar_content->bind_result($title,$start,$end,$link);
$result = array();
while($calendar_content->fetch()) {
//validate using user type where user redirect
$result[] = array('title'=>$title,'start'=>$start,'end'=>$end,'url'=>$link);
header('Content-type: application/json');
}
echo json_encode($result);
?>

Related

lib fullCalendar, calendar isn't rendering in the page... i'm using contats and events in my calendar

my homepage is the callendar and look like this:
<?php
include_once("banco/conexao.php");
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<script src='https://cdn.jsdelivr.net/npm/fullcalendar#6.1.4/index.global.min.js'></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
header: {
left: 'prev,next today',
center: 'title',
right: 'dayGridMonth,timeGridWeek,timeGridDay,listYear'
},
views: {
listYear: {
type: 'listYear',
buttonText: 'Year'
}
},
initialView: 'dayGridMonth',
locale: 'pt-br',
events: [
<?php include 'eventos_json.php'; ?>
<?php include 'contatos_json.php'; ?>
]
});
calendar.render();
});
</script>
</head>
<body>
<div id='calendar'></div>
</body>
</html>
I created 2 files to prepare the event and contact data
my event_json.php file:
<?php
include_once 'banco/conexao.php';
// database connection
$conn = getConexao();
// recover events from database
$queryEventos = "SELECT * FROM eventos";
$resultEventos = mysqli_query($conn, $queryEventos);
// Convert event information into a format that FullCalendar understands
$eventos = array();
while ($evento = mysqli_fetch_assoc($resultEventos)) {
$nomeEvento = $evento['nomeEvento'];
$dataEvento = $evento['dataEvento'];
$horaEvento = $evento['horaEvento'];
$tipoEvento = $evento['tipoEvento'];
$organizadorEvento = $evento['organizadorEvento'];
$telefoneEvento = $evento['telefoneEvento'];
$localEvento = $evento['localEvento'];
$eventos[] = array(
'title' => $nomeEvento,
'start' => $dataEvento . 'T' . $horaEvento,
'extendedProps' => array(
'tipoEvento' => $tipoEvento,
'organizadorEvento' => $organizadorEvento,
'telefoneEvento' => $telefoneEvento,
'localEvento' => $localEvento,
),
);
}
mysqli_close($conn);
echo json_encode($eventos);
?>
my contact_json.php file
<?php
include_once 'banco/conexao.php';
$conn = getConexao();
$queryContatos = "SELECT * FROM contatos";
$resultContatos = mysqli_query($conn, $queryContatos);
$contatos = array();
while ($contato = mysqli_fetch_assoc($resultContatos)) {
$nomeContato = $contato['nomeContato'];
$dataNascContato = $contato['dataNascContato'];
$emailContato = $contato['emailContato'];
$telefoneContato = $contato['telefoneContato'];
$sexoContato = $contato['sexoContato'];
$contatos[] = array(
'title' => $nomeContato,
'start' => $dataNascContato,
'allDay' => true,
'extendedProps' => array(
'emailContato' => $emailContato,
'telefoneContato' => $telefoneContato,
'sexoContato' => $sexoContato,
),
);
}
// Retorna os contatos no formato JSON
mysqli_close($conn);
echo json_encode($contatos);
?>
i'm not from a english country, so my code is in another language (portuguese)
my localhost is like this,
the calendar is not showing :
im here because not even chatgbt can help me anymore

How to dispaly resources and events from database to fullcalendar?

I've been developing a full-calendar with a resource column and draggable events. I'm stuck at displaying the resources and events from the database on the calendar.
The data could be fetched successfully, as I can see it in the response tab in an array but it is not getting displayed on the calendar at all. Even the front-end doesn't seem to be working fully as while adding the resource, it is not even getting displayed temporarily. The files are getting called in the network tabs and I can see the correct results in the response tab, so I'm guessing it's the display that is not working maybe I haven't installed proper plugins or something. Can you please check what is wrong?
There were a few similar questions on this site, but everyone seemed to have different issues. I can post other related files as well, let me know if you would like to see.
Here's the code:
document.addEventListener("DOMContentLoaded", function() {
var containerEl = document.getElementById("external-events");
var checkbox = document.getElementById("drop-remove");
new FullCalendarInteraction.Draggable(containerEl, {
itemSelector: ".fc-event",
eventData: function(eventEl) {
return {
title: eventEl.innerText
};
}
});
var calendarEl = document.getElementById("calendar");
var calendar = new FullCalendar.Calendar(calendarEl, {
schedulerLicenseKey: "GPL-My-Project-Is-Open-Source",
plugins: ["interaction", "resourceTimeline"],
header: {
left: "promptResource today prev,next",
center: "title",
right: "resourceTimelineDay,resourceTimelineWeek"
},
customButtons: {
promptResource: {
text: "+ room",
click: function() {
var title = prompt("Room name");
console.log(title);
if (title) {
fetch("add_resources.php", {
method: "POST",
headers: {
'Accept': 'text/html'
},
body: encodeFormData({"title": title}),
})
.then(response => response.text())
.then(response => {
calendar.addResource({
id: response,
title: title
});
})
.catch(error => console.log(error));
}
}
}
},
editable: true,
aspectRatio: 1.5,
defaultView: "resourceTimelineDay",
resourceLabelText: "Rooms",
resources: "all_resources.php",
droppable: true,
drop: function(info) {
if (checkbox.checked) {
info.draggedEl.parentNode.removeChild(info.draggedEl);
}
},
eventLimit: true,
events: "all_events.php",
displayEventTime: false,
eventRender: function(event, element, view) {
if (event.allDay === "true") {
event.allDay = true;
} else {
event.allDay = false;
}
},
selectable: true,
selectHelper: true,
eventReceive: function(info) {
console.log(calendar.getResources());
console.log(info.event);
var eventData = {
title: info.event.title,
start: moment(info.event.start).format("YYYY-MM-DD HH:mm"),
end: moment(info.event.start).format("YYYY-MM-DD HH:mm"),
resourceid: info.event._def.resourceIds[0]
};
console.log(eventData);
//send the data via an AJAX POST request, and log any response which comes from the server
fetch("add_event.php", {
method: "POST",
headers: {
Accept: "application/json"
},
body: encodeFormData(eventData)
})
.then(response => console.log(response))
.catch(error => console.log(error));
}
});
calendar.render();
});
const encodeFormData = data => {
var form_data = new FormData();
for (var key in data) {
form_data.append(key, data[key]);
}
return form_data;
};
form.php
<link href='https://unpkg.com/#fullcalendar/core#4.4.0/main.min.css' rel='stylesheet' />
<link href='https://unpkg.com/#fullcalendar/daygrid#4.4.0/main.min.css' rel='stylesheet' />
<link href='https://unpkg.com/#fullcalendar/timegrid#4.4.0/main.min.css' rel='stylesheet' />
<script src='https://unpkg.com/#fullcalendar/core#4.4.0/main.min.js'></script>
<script src='https://unpkg.com/#fullcalendar/interaction#4.4.0/main.min.js'></script>
<script src='https://unpkg.com/#fullcalendar/daygrid#4.4.0/main.min.js'></script>
<script src='https://unpkg.com/#fullcalendar/timegrid#4.4.0/main.min.js'></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<link href='https://unpkg.com/#fullcalendar/timeline#4.4.0/main.min.css' rel='stylesheet' />
<link href='https://unpkg.com/#fullcalendar/resource-timeline#4.4.0/main.min.css' rel='stylesheet' />
<script src='https://unpkg.com/#fullcalendar/timeline#4.4.0/main.min.js'></script>
<script src='https://unpkg.com/#fullcalendar/resource-common#4.4.0/main.min.js'></script>
<script src='https://unpkg.com/#fullcalendar/resource-timeline#4.4.0/main.min.js'></script>
<link href="main.css" rel="stylesheet">
<script src='main.js'></script>
<div id='external-events'>
<p>
<strong>Draggable Events</strong>
</p>
<div class='fc-event'>My Event 1</div>
<div class='fc-event'>My Event 2</div>
<div class='fc-event'>My Event 3</div>
<div class='fc-event'>My Event 4</div>
<div class='fc-event'>My Event 5</div>
<p>
<input type='checkbox' id='drop-remove' />
<label for='drop-remove'>remove after drop</label>
</p>
</div>
<div id='calendar-container'>
<div id='calendar'></div>
</div>
all_resources.php
<?php
require 'connection.php';
$conn = DB::databaseConnection();
$json = array();
$sql = "SELECT * FROM resources ORDER BY resourceId";
$result = $conn->prepare($sql);
$result->execute();
$alldata = array();
while($row = $result->fetch(PDO::FETCH_ASSOC))
{
array_push($alldata, $row);
}
echo json_encode($alldata);
?> ```
all_events.php
<?php
require 'connection.php';
$conn = DB::databaseConnection();
$json = array();
$sql = "SELECT * FROM Events ORDER BY id";
$result = $conn->prepare($sql);
$result->execute();
$alldata = array();
while($row = $result->fetch(PDO::FETCH_ASSOC))
{
array_push($alldata, $row);
}
echo json_encode($alldata);
?>
The response from all_resources.php looks like this:
[
{"resourceId":"104","resourceTitle":"TESET"},
{"resourceId":"105","resourceTitle":"AA"},
{"resourceId":"106","resourceTitle":"HM"},
{"resourceId":"107","resourceTitle":"TEST"}
]
The response from all_events.php looks like this:
[
{"id":"65","resourceId":"104","title":"My Event 1","start":"2020-04-06","end":"2020-04-06"},
{"id":"66","resourceId":"105","title":"My Event 1","start":"2020-04-06","end":"2020-04-06"}
]
Your resource data is not in the format specified by fullCalendar. The field names you supply in the JSON must be exactly as mentioned in the resource parsing documentation - e.g. id for the resource ID, title for the title, etc. If you don't do this, fullCalendar cannot understand the data and will not display the resources.
To modify your server-side code to achieve this you have two options:
1) change your database column names in your resources table to match what fullCalendar requires. So you'd change resourceId to id and resourceTitle to title. This should be sufficient, and would not require any changes to your PHP code.
OR
2) change your all_resources.php PHP code so it generates a new array for each data row, containing the same data but with different property names, so that these names will be encoded in the JSON instead of the column names from the database:
<?php
require 'connection.php';
$conn = DB::databaseConnection();
$json = array();
$sql = "SELECT * FROM resources ORDER BY resourceId";
$result = $conn->prepare($sql);
$result->execute();
$alldata = array();
while($row = $result->fetch(PDO::FETCH_ASSOC))
{
$resource = array(
"id" => $row["resourceId"],
"title" => $row["resourceTitle"]
);
array_push($alldata, $resource);
}
echo json_encode($alldata);
?>

jQuery Full Calendar Events are not loading from Database in PHP,Codeigniter3

I implemented jQuery Full Calendar, as a separate module...That time it worked good. Now I want to show events after user logged in...User Login done... But issue with loading events only, events are added into Database.. But they won't be loaded into Calendar view
To redirect load.php, I used echo site_url('controller/method'),redirect('controller/method'). When I used redirect method it gives me 'json' data(the data which returned from load.php)
**views/calendar_view.php:**
<script>
$(document).ready(function(){
var calendar = $('#calendar').fullCalendar({
editable:true,
header:{
left:'prev,next today',
center:'title',
right:'month,agendaWeek,agendaDay'
},
events:'<?php echo site_url('Home/load'); ?>', /* redirect('Home/load');//<?php //$this->load->view('load')?>*/
selectable:true,
selectHelper:true,
**views/load.php:**
if($conn==false)
{
echo "Failed to connect to the Database | <br/>";
die(print_r(sqlsrv_errors(),true));
}
$timezone = new DateTimeZone("UTC");
$sql = "select * from events";
$stmt = sqlsrv_query($conn,$sql);
if($stmt == false)
{
die(print_r(sqlsrv_errors(),true));
}
while($row = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC))
{
$data[] = array(
'id' => $row['id'],
'title' => $row['title'],
'start' => $row['start_event']->format("Y-m-d H:i:s"),
'end' => $row['end_event']->format("Y-m-d H:i:s")
);
}
I want to show events, after employee logged in successfully
It looks like views/load.php does not return anything, the jquery plugin expects a json object, so add the following to load.php
echo json_encode($data);
Furthermore as I remember the events in the plugin does not allow url's directly.
Therefore you will need to load the data from the url. Did not test it, but should be something like below.
$.get('<?php echo site_url('Home/load'); ?>', function(data) {
var calendar = $('#calendar').fullCalendar({
editable:true,
header:{
left:'prev,next today',
center:'title',
right:'month,agendaWeek,agendaDay'
},
events:data.parseJSON(),
selectable:true,
selectHelper:true,
});
You can check in your browser developer tools if the data was loaded correctly:
F.e. Chrome: https://developers.google.com/web/tools/chrome-devtools/network/reference

Retrieve PHP Array with JSON and use the array in javascript to populate a playlist

I try to understand how it work. At the beginning, I was using inside my html code a php array with db and after that I was extracting my array inside my playlist.
Here the example:
<?php
$fileinfo=array();
$count=0;
//SQL Query
$query = "select track, artiste, album, emplacement, duration, poster from tempo where genre like '%%' ORDER BY no_track";
$con=mysqli_connect("localhost","user","password","db_table");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$resultat = mysqli_query($con,$query);
while($row = mysqli_fetch_array($resultat))
{
$row['emplacement'] = str_replace("../", "../../", $row['emplacement']);
$row['poster'] = str_replace("../", "../../", $row['poster']);
$row['duration'] = str_replace("00:", "", $row['duration']);
$info = '{artist:"'.$row['artiste'].'", title:"'.$row['track'].'", album:"'.$row['album'].'", mp3:"'.$row['emplacement'].'", cover:"'.$row['poster'].'", duration:"'.$row['duration'].'"}';
array_push($fileinfo, $info);
}
mysqli_close($con);
?>
...
$('#player').ttwMusicPlayer(
[
<?php
//for each file in directory
$arrlength=count($fileinfo);
for($x=0;$x<$arrlength;$x++)
{
if ($x < ($arrlength - 1))
{
echo $fileinfo[$x].",\n\t\t";
}else
{
echo $fileinfo[$x]."\n\t\t";
}
}
//the result look like this:
//{artist:"Boy Sets Fire", title:"After the Eulogy", album:"After The Eulogy",
mp3:"../../music/Punk/Hardcore_Punk/Boy_Sets_Fire_-_After_the_Eulogy-2000-
JAH/01_After_the_Eulogy-JAH.mp3",
cover:"../../music/Punk/Hardcore_Punk/Boy_Sets_Fire_-_After_the_Eulogy-2000-
JAH/Folder.jpg", duration:"03:31"},
?>
],
To use everything more dynamically, I try to use JSON with PHP inside my javascript
And my code look like this:
var sourceplayer =
{
datatype: "json",
datafields: [
{ name: 'artiste' },
{ name: 'title' },
{ name: 'album' },
{ name: 'mp3' },
{ name: 'cover' },
{ name: 'duration' }
],
url: 'player.php'
};
$('#player').ttwMusicPlayer(
[
],
So afert url: 'player.php', I don't know how to work with result. It's an array of data like this: "Rows":[{"no_track":"1","track":"Grandma Dynamite","artiste":"24-7 Spyz","album":"Harder Than You","genre":"Alternative","year":"1989","duration":"00:03:44"}
And I want to use it inside the bracket of $('#player').ttwMusicPlayer(
Please give me a cue or an simple example to help me with this. I'm not using pure jplayer but a similar one.
Thanks in advance
Regards,
Eric
PHP json_encode - http://us2.php.net/json_encode
<?php
$fileinfo=array();
$count=0;
//SQL Query
$query = "select track, artiste, album, emplacement, duration, poster from tempo where genre like '%%' ORDER BY no_track";
$con=mysqli_connect("localhost","user","password","db_table");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$resultat = mysqli_query($con,$query);
while($row = mysqli_fetch_array($resultat))
{
$fileinfo[] = array(
'mp3' => str_replace("../", "../../", $row['emplacement']),
'cover' => str_replace("../", "../../", $row['poster']),
'duration' => str_replace("00:", "", $row['duration']),
'artist' => $row['artiste'],
'title' => $row['track'],
'album' => $row['album']
);
}
mysqli_close($con);
?>
...
$('#player').ttwMusicPlayer(<?php echo json_encode($fileinfo); ?>);

jTable Not Displaying

I'm trying to build a website including jQuery and jTable. As such, I've been trying to use the example jTable scripts that the website provides, but I can't seem to get any input returned. The file paths all work, and I check to make sure jQuery was loaded (it was). I'm really not sure what I'm doing wrong, if anything. Thanks!
jTable file:
<html>
<head>
<link href="JQueryUI/css/smoothness/jquery-ui-1.8.21.custom.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="jquery.js"></script>
<link href="jtable/themes/standard/blue/jtable_blue.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="jtable/jquery.jtable.js"></script>
</head>
<title>Under Construction</title>
Hello World
<div id="PersonTableContainer"></div>
<script type="text/javascript">
$(document).ready(function () {
$('#PersonTableContainer').jtable({
title: 'Table of people',
actions: {
listAction: 'PersonList.php'
createAction: 'CreatePerson.php'
updateAction: 'UpdatePerson.php'
deleteAction: 'DeletePerson.php'
},
fields: {
PersonId: {
key: true,
create: false,
edit: false,
list: false
},
Name: {
title: 'Author Name',
width: '40%'
},
Age: {
title: 'Age',
width: '20%'
},
RecordDate: {
title: 'Record date',
width: '30%',
type: 'date',
create: false,
edit: false
}
}
});
$('#PersonTableContainer').jtable('load');
});
PersonList.php
<?php
$link = new mysqli("localhost", "user", "pass", "people");
$query = "SELECT * FROM people";
$results = mysqli_query($link, $query);
$rows = array();
while($row = mysqli_fetch_assoc($results))
{
$rows[] = $row;
}
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['Records'] = $rows;
print json_encode($jTableResult);
}
?>
PersonList.php returns the proper output in terminal, it just doesn't seem to display anything in the website/jTable.
Try below and let me know if it works, I don't have a lot of experience with it but I even made a custom search function for it if you need it.
I use a single actions file and I use $_REQUEST for it though, not different files like you do.
//Get records from database
$result = mysql_query("SELECT * FROM people;");
//Add all records to an array
$rows = array();
while($row = mysql_fetch_array($result))
{
$rows[] = $row;
}
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['Records'] = $rows;
print json_encode($jTableResult);
to debug this I'd start with three angles:
1. look at the AJAX response in developer tools. In Chrome that is on the Network tab, filtering by XHR. First verify that the AJAX call is being made and look at the response.
2. verify that the AJAX response is getting into the jtable context. Just add these lines under your fields attribute:
fields: {
...
},
recordsLoaded: function(event, data) {
console.log(data);
}
3. in the browser console expand this console.log object and look at the array items. jtable is case sensitive so the resulting parameters must have the same spelling and capitalization. its usually pretty easy to just change the field names in the jtable description to match the db field names.

Categories

Resources