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

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

Related

php - Display Events with Form Submit (FullCalendar)

Good day!
I am working on a small personal project with FullCalendar. So in the code below, I have written a function that displays the events when the user searches for that event when a keyword is entered. (e.g. "meeting")
function load($pdo)
{
try {
if (isset($_POST['search'])) {
//run sql connection and query
$term = $_POST['term'];
$data = array();
$sql = "SELECT * FROM events WHERE keyword LIKE '%$term%'";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll();
//output events data from db in array using foreach loop
foreach ($result as $row) {
$description = $row['description'];
$sentence = preg_replace('/(.*?[?!.](?=\s|$)).*/', '\\1', $description);
if (($row['allDay'] == '1') == 1) {
$data[] = array(
'id' => $row["id"],
'title' => $row["title"],
'start' => $row["s_date"],
'description' => $sentence,
'end' => $row["e_date"],
'url' => "event.php?id=".$row['id'],
'backgroundColor' => $row['bg_color'],
'borderColor' => $row['brdr_Color'],
'keywords' => $row['keyword'],
'category' => $row['category']
);
} else {
$data[] = array(
'id' => $row["id"],
'title' => $row["title"],
'start' => $row["s_date"],
'description' => $sentence,
'end' => $row["e_date"],
'url' => "event.php?id=".$row['id'],
'backgroundColor' => $row['bg_color'],
'borderColor' => $row['brdr_Color'],
'keywords' => $row['keyword'],
'category' => $row['category']
);
}
}
//echo and convert array to JSON representation
echo json_encode($data);
}
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
}
//execute load function
load($pdo);
The results are echoed in a json_encoded function and are loaded from jQuery.
$(document).ready(function () {
var calendar = $("#calendar").fullCalendar({
displayEventTime: false,
editable: false,
header: {
left: "prev,next today",
center: "title",
right: "listMonth, month,agendaWeek,agendaDay",
},
eventRender: function (event, element, view) {
$(element).tooltip({
title: event.description,
});
},
events: "load.php",
});
});
After submitting the form/hitting the submit button, the events are not returned or displayed. Is there something I'm missing in my code, or am I missing a procedure?
I hope I described my issue to your best of understanding and I hope to learn from this and better improve my code in the future.

How to fix failure parsing json using FullCalendar.js

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);
?>

Saving kartik select2 widget data with a model

Am using kartik select2 widget and i would like it to save data to the database by passing it to the controller.
I have tried this
1. the select2 widget
<?php $form = ActiveForm::begin(['id'=>$model->formName()]); ?>
<?php
echo $form->field($model, 'unitid')->widget(Select2::classname(), [
'data' => ArrayHelper::map($model2,'unitid','unitname'),
'language' => 'de',
'options' => ['multiple' => true, 'placeholder' => 'Select a Unit '],
'pluginOptions' => [
'allowClear' => true
],
]);
?>
<?php ActiveForm::end(); ?>
The javascript code to save data on form submit which is on the view:
<?php
$script = <<< JS
$('form#{$model->formName()}').on('beforeSubmit', function(e)
{
var \$form = $(this);
console.log(\$form.serialize());
$.post(
\$form.attr("action"),
\$form.serialize()
)
.done(function(result) {
console.log("Succesifully saved" + result);
}).fail(function(err)
{
console.log("failed to save" + err);
});
return false;
});
JS;
$this->registerJs($script);
?>
This generates this output on the console(for the serialized form output
_csrf=TGMzaDRINnEHFgM5RjIPICc2bBoZAWZAOBIGAnAeVSF4GUQteThUFw%
3D%3D&Unitslocation%5Bunitid%5D=&Unitslocation%5Bunitid%5D%5B%5D=9
the output is always passed as a string that is after trying
echo json_encode($model->unitid);
On the controller it returns a string instead of an integer
that is
["5"]
How can i convert ($model->unitid) to integer for the post params
Just use
$model->unitid = (int) $model->unitid;
Thats all.

MySQL data into FullCalendar

EDIT 2
I have the array at the correct format but nothing added to calendar:
EDIT
I want to get data from mysql and display it on fullcalendar. I have this PHP code:
<?php
//Set error reporting on
error_reporting(E_ALL);
ini_set("display_errors", 1);
//Include connection file
require_once('global.php');
//Json and PHP header
header('Content-Type: application/json');
$eventss = array();
$user = $_SESSION['username'];
$id_logged = $_SESSION['login_id'];
$search_date = "SELECT * FROM appointment INNER JOIN patient ON appointment.patient_id = patient.id WHERE appointment.id_logged = :id_logged";
$search_date_stmt = $conn->prepare($search_date);
$search_date_stmt->bindValue(':id_logged', $id_logged);
$search_date_stmt->execute();
$search_date_stmt_fetch = $search_date_stmt->fetchAll();
$search_date_stmt_count = $search_date_stmt->rowCount();
foreach($search_date_stmt_fetch as $row)
{
$events[] = array( 'title' => $row['patient_name'], 'start' => date('Y-m-d',$row['date_app']), 'end' => date('Y-m-d',$row['date_app']), 'allDay' => false);
array_push($events, $event);
}
echo json_encode($event);
?>
The array that should be returned to fullcalendar so it can display it should be like:
'id'=>'value', 'title'=>'my title', 'start'=>...etc
But what the array I am seeing in the XHR is like:
Here is fullcalendar script (no errors at the console):
<script>
(function ($) {
$(document).ready(function() {
$('#calendar').fullCalendar({
eventSources: [
// your event source
{
url: 'fullcalendar/get-events.php',
error: function() {
alert('there was an error while fetching events!');
},
color: 'yellow', // a non-ajax option
textColor: 'black' // a non-ajax option
}
// any other sources...
]
});
});
})(jQuery);
</script>
I think you have problem with array you are using and you dont have ID for event, it supposee patient id to b I made some changes on your code please try it .
foreach($search_date_stmt_fetch as $row)
{
$event = array( 'id' => $row['patient_id'], 'title' => $row['patient_name'], 'start' => date('Y-m-d',strtotime($row['date_app'])), 'end' => date('Y-m-d',strtotime($row['date_app'])), 'allDay' => false);
array_push($events, $event);
}
echo json_encode($events);
You are mixing $event, $events and $eventss (unused).
It should read :
foreach($search_date_stmt_fetch as $row) {
$event = array( 'id' => $row['patient_id'], 'title' => $row['patient_name'], 'start' => date('Y-m-d',$row['date_app']), 'end' => date('Y-m-d',$row['date_app']), 'allDay' => false);
array_push($events, $event);
}
echo json_encode($events);
it depends on version of full calendar , there are two version v2 , v1
the required properties for the event object is title,start
if you are working with version v2, u need to convert the date to Moment, the version v2 is completely working on moment objects.
after getting the data from server, we can convert it like this
in js file:
$.map(data, function (me) {
me.title = me.title, // this is required
me.start = moment(me.start).format(); // this is required
me.end = moment(me.end).format();
}
$('#calendar').fullCalendar('addEventSource', data);

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