AJAX data not posting using FullCalendar when trying to update - php

I have a calendar.php file which looks up "php/get-events" to display calendar events from the database (This currently works as expected). I am trying to use "php/calendarupdate" to then update the database with the new start/end times that have been dragged, but the data posting to this page always comes back as undefined, so it's not finding it for some reason.
"Calendar.php"
<script>
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
headerToolbar: {
left: 'prev,next today',
center: 'title',
right: 'dayGridMonth,timeGridWeek,timeGridDay,listWeek'
},
initialDate: '2021-03-18',
editable: true,
eventDrop: function(event, delta) {
start=moment(event.start).format('Y-MM-DD HH:mm:ss');
end=moment(event.end).format('Y-MM-DD HH:mm:ss');
$.ajax({
url: 'php/calendarupdate.php',
data: 'title=' + event.title + '&start='+ event.start +'&end=' + event.end + '&id=' + event.id ,
type: "POST",
success: function(json) {
alert("Updated Successfully");
}
});
},
navLinks: true, // can click day/week names to navigate views
dayMaxEvents: true, // allow "more" link when too many events
events: {
url: '/php/get-events.php',
failure: function() {
document.getElementById('script-warning').style.display = 'block'
}
},
loading: function(bool) {
document.getElementById('loading').style.display =
bool ? 'block' : 'none';
}
});
calendar.render();
});
</script>
The following is where I get the data which successfully displays events on the calendar.
"php/get-events.php"
$stmt = $pdo->prepare("Select id,task_name,start,end,notes,task_type,status from tasks where attendees like ".$attendees);
$stmt->execute();
//$stmt->debugDumpParams();
foreach ($stmt as $row){
$rawdata[] = array('id' => $row['id'], 'title'=> $row['task_name'], 'start'=> $row['start'], 'end'=> $row['end']);
}
$rawdata = json_encode($rawdata);
echo $rawdata;
The following is the update file, which it is getting into ok, but the echo's I try to display are all undefined.
/* Values received via ajax */
echo "id -".$_POST['id'];
echo "start -".$_POST['start'];
echo "end -".$_POST['end'];
// update the records
$stmt = $pdo->prepare('UPDATE tasks SET start=?, end=? WHERE id=?');
$stmt->execute($_POST['start'], $_POST['end'], $_POST['id']);
$stmt->debugDumpParams();
It may be something simple, but from the documentation I've read, I can't seem to figure out why my variables are not posting successfully. Thanks.

You have the wrong syntax for your eventDrop signature. See https://fullcalendar.io/docs/eventDrop
It should be
eventDrop: function(info) {
And then replace
event.start
and
event.end
with
info.event.start
and
info.event.end
This will get the information you need correctly from the data which fullCalendar supplies.

Related

How to populate Jvector Map with countries from database?

(I am new to Javascript and jQuery..) I have a dashboard and I want to display a map that shows the countries where participants of a particular event are coming from. With this, I opted with Jvector Map. I am having a hard time displaying the countries in the map, coming from my database.
dashboard.js
var mapData = {};
$('#world-map').vectorMap({
map: 'world_mill_en',
backgroundColor: "transparent",
regionStyle: {
initial: {
fill: '#e4e4e4',
"fill-opacity": 0.9,
stroke: 'none',
"stroke-width": 0,
"stroke-opacity": 0
}
},
series: {
regions: [{
values: function() {
$.ajax({
url:"includes/sql/fetchcountries.php",
method:"GET",
data:mapData,
dataType:"json",
success: function(data){
mapData = data;
console.log(mapData);
}
})
},
scale: ["#1ab394", "#22d6b1"],
normalizeFunction: 'polynomial'
}]
},
});
fetch.php
<?php
require '../auth/dbh.inc.auth.php';
$id = $_SESSION['ntc_id'];
$stmt = $conn->prepare("SELECT DISTINCT(participants.p_country) FROM ntc_participants
INNER JOIN participants ON participants.p_id=ntc_participants.p_id_fk
WHERE ntc_participants.ntc_id_fk=?");
$data = array();
mysqli_stmt_bind_param($stmt, "i", $id);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows === 0);
if($row = $result->fetch_assoc()) {
$data[] = [
$row['p_country'] => 0 ]; //the value 0 is just a placeholder.. The jvector map feeds on this format: "US":298, "SA": 200
}
echo json_encode($data);
?>
Could anyone be gracious enough to walk me through all the wrong things I'm doing in my code? Appreciate all the help! :)
Ajax is asynchronous, so You are creating the map before the data has been downloaded.
Initialize the map with empty values for Your region:
$('#world-map').vectorMap({
...
values: {}
...
});
Then, whenever You need to show the data, set it dynamically:
$.get("includes/sql/fetchcountries.php", function(data) {
var mapObj = $("#world-map").vectorMap("get", "mapObject");
mapObj.series.regions[0].setValues(data);
});
During the ajax invocation and data download maybe You can show a spinner (please look at beforeSend inside the jQuery full ajax documentation: https://api.jquery.com/jquery.ajax/).
Here is the reference for setValues:
http://jvectormap.com/documentation/javascript-api/jvm-dataseries/
http://api.worldbank.org/v2/country/all/indicator/NY.GDP.PCAP.PP.CD?format=json&date=2018
This link will give you up-to-date stats for most common indicators via json - and then you can pluck whatever data that you like. I don't have all the code yet, as I am working on this today too.
This answers the question above whenever your database can also present JSON
document.addEventListener('DOMContentLoaded', () => {
console.log("loaded")
fetchCountryData()
})
function fetchCountryData () {
fetch('http://api.worldbank.org/v2/country/all/indicator/NY.GDP.PCAP.PP.CD?format=json&date=2018')
//
.then(resp => resp.json())
.then(data => {
let country.id = data[1]
let indicator.id = data[1]
create-GDP-Data(country.id,indicator.id)
})
}
function create-GDP-Data(country.id,indicator.id){
let gdpData = ?
}
$('#world-map-gdp').vectorMap({
map: 'world_mill',
series: {
regions: [{
values: gdpData,
scale: ['#C8EEFF', '#0071A4'],
normalizeFunction: 'polynomial'
}]
},
onRegionTipShow: function(e, el, code){
el.html(el.html()+' (GDP - '+gdpData[code]+')');
}
});

Search through FullCalendar

I am building a college timetable with FullCalendar, php and mysql.
Events are created when you click in the calendar field; you assign a name for the event, a professor and a room. The event is saved in an sql databse.
I would like to add a search bar which would search through the timetable; a user could search for either professor, room number, event name. The timetable would update as the user types and it would re-fetch the event with that room number/event name/professor name.
Anyone have any clue how to do this?
This is the code i am using for rendering events from the mysql:
$sql = "SELECT id, title, naem, mentor, start, end, color FROM events ";
$req = $bdd->prepare($sql);
$req->execute();
$events = $req->fetchAll();
...
...
$(document).ready(function() {
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
height:595,
defaultView: 'agendaWeek',
minTime: "07:00:00",
maxTime: "16:00:00",
editable: true,
eventLimit: true,
selectable: true,
selectHelper: true,
firstDay:"1",
select: function(start, end) {
$('#ModalAdd #start').val(moment(start).format('YYYY-MM-DD HH:mm:ss'));
$('#ModalAdd #end').val(moment(end).format('YYYY-MM-DD HH:mm:ss'));
$('#ModalAdd').modal('show');
},
eventRender: function(event, element) {
element.bind('dblclick', function() {
$('#ModalEdit #id').val(event.id);
$('#ModalEdit #title').val(event.title);
$('#ModalEdit #naem').val(event.naem);
$('#ModalEdit #mentor').val(event.mentor);
$('#ModalEdit #color').val(event.color);
$('#ModalEdit').modal('show');
});
element.find('.fc-title').append("<br/>" + event.naem + "<br/>" + event.mentor);
},
eventDrop: function(event, delta, revertFunc) {
edit(event);
},
eventResize: function(event,dayDelta,minuteDelta,revertFunc) {
edit(event);
},
events: [
<?php foreach($events as $event):
$start = explode(" ", $event['start']);
$end = explode(" ", $event['end']);
if($start[1] == '00:00:00'){
$start = $start[0];
}else{
$start = $event['start'];
}
if($end[1] == '00:00:00'){
$end = $end[0];
}else{
$end = $event['end'];
}
?>
{
id: '<?php echo $event['id']; ?>',
title: '<?php echo $event['title']; ?>',
naem: '<?php echo $event['naem']; ?>',
mentor: '<?php echo $event['mentor']; ?>',
start: '<?php echo $start; ?>',
end: '<?php echo $end; ?>',
color: '<?php echo $event['color']; ?>',
},
<?php endforeach; ?>
]
});
function edit(event){
start = event.start.format('YYYY-MM-DD HH:mm:ss');
if(event.end){
end = event.end.format('YYYY-MM-DD HH:mm:ss');
}else{
end = start;
}
id = event.id;
Event = [];
Event[0] = id;
Event[1] = start;
Event[2] = end;
$.ajax({
url: 'editEventDate.php',
type: "POST",
data: {Event:Event},
success: function(rep) {
if(rep == 'OK'){
alert('Spremljeno!');
}else{
alert('Nešto zajebaje...');
}
}
});
}
});
</script>
An autocomplete plugin such as this will help with the UI part: https://jqueryui.com/autocomplete/
Using this your user can find the IDs of the people / rooms / event names involved and choose one from the list of possibilities. You will need an ajax call and an associated server endpoint which will search the database based on what the user types into the box and return any matching results.
Then in fullCalendar use this format for your event feed https://fullcalendar.io/docs/event_data/events_function/ so that you can pass the selected ID from the autocomplete to the server as an extra parameter when fetching events.
Next listen to the autocomplete's "select" event (http://api.jqueryui.com/autocomplete/#event-select) and when a value is chosen, call "refetchEvents" (https://fullcalendar.io/docs/event_data/refetchEvents/) on the fullCalendar. This will update your events list, restricting it by the specific person/room/event ID as well as the standard parameters (i.e. those being the current start/end dates of the visible view).

Send Ajax data to Laravel controller

I am using fullcalendar, I need need to create a new event when user clicks on a specific date, I am using Laravel controller to store the data send by ajax request. I can create an event on calendar, but I cant send the data to controller and moreover browser tab freezes after creating the event. Anyone can correct where I am wrong? or provide better solution to the problem.
select: function(start, end, allDay) {
var title = event_name;// Event Title:
var eventData;
if (title) {
eventData = { //creates a new event on the calendar
title: title,
start: start,
end: end,
allDay: allDay
};
$('#calendar').fullCalendar('renderEvent', eventData, true); // stick? = true
$.ajax({
data:eventData,
type: 'POST',
url:"/projects/calendar/store", // your url
beforeSend: function (request) {
return request.setRequestHeader('X-CSRF-Token', $("meta[name='csrf-token']").attr('content'));
},
success: function(response) {
console.log(response);
}
});
}
$('#calendar').fullCalendar('unselect');
},
This is my Route file, I have tried both get and post but none is working.
Route::get('/projects/calendar/store','FrontEndController#calendarStore');
This is the Controller, it will only process data sent by ajax request but no view.
public function calendarStore(Request $request)
{
$calendar = new Calendar;
Input::all();
$userId = Auth::user()->id;
$event_title =$request->input('title');
$start =$request->input('start');
$end =$request->input('end');
$calendar_event = Calendar::create([
'user_id' => $userId, // I can get the user ID
'project_id' => 2,
'event_title' => $event_title,
'start_date' =>$start,
'end_date' => $end
]);
}
replace your declaration of your ajax data parameter like this:
//creates a new event on the calendar
eventData = {
"title": title,
"start": start,
"end": end,
"allDay": allDay
};
I did the following modifications: and its working as Expected, once user click/selects on the specific day/day's it will ask for title and and save the event in database.
select: function(start, end, allDay) {
var title = prompt('Are u sure you want to apply for job? Yes/No:');// Event Title:
var start_time = moment(start).format();
var end_time = moment(end).format(); //onclick get date
var eventData;
if (title) {
eventData = {
title: title,
start: start,
end: end,
allDay: allDay
};
$('#calendar').fullCalendar('renderEvent', eventData, true); // stick? = true
$.ajax({
type: 'GET',//POST changed to GET
url: "/projects/calendar/store", // your url
data: { //event data from global variable
title: event_name,
start: start_time,
end: end_time,
event_id:event_id
},
beforeSend: function (request) {
return request.setRequestHeader('X-CSRF-Token', $("meta[name='csrf-token']").attr('content'));
},
success: function(response) {
console.log(response);
}
});
}
$('#calendar').fullCalendar('unselect');
},
Updated Route
Route::get('/projects/calendar/store','FrontEndController#calendarStore');
Updated Controller
public function calendarStore(Request $request)
{
$userId = Auth::user()->id;
$event_title =$request->get('title');
$start =$request->input('start');
$end =$request->input('end');
$project_id= $request->input('event_id');
$calendar_event = Calendar::create([
'user_id' => $userId,
'project_id' => $project_id,
'event_title' => $event_title,
'start_date' =>$start,
'end_date' => $end
]);
return $calendar->all();
}

jQuery FullCalendar doesn't show events issue in FireFox 33.0

I'm trying to set up jQuery FullCalendar by providing data as json feed trough fullcalendar events function. So basically this is my js code:
var calendar = $('#calendar').fullCalendar({
editable: true,
firstDay: 1,
header: {
left: 'prev, next today',
center: 'title',
right: 'month, agendaWeek, agendaDay'
},
events:
{
url: 'events.php',
type: 'POST',
cache: false,
error: function() {
alert('ERROR');
},
color: 'blue'
}
});
And my code from events.php which pulls data from database and makes as JSON feed + converting date to ISO8601 date strings as sayd in documentation.
// Query that retrieves events
$q = "SELECT * FROM evenement ORDER by id";
$r = mysqli_query($dbc, $q);
while ($row = mysqli_fetch_assoc($r))
{
$s = new DateTime($row['start']);
$e = new DateTime($row['end']);
$row['start'] = $s->format(DATE_ISO8601);
$row['end'] = $e->format(DATE_ISO8601);
$json[] = $row;
}
echo json_encode($json);
In IE11 and Chrome it shows all the events in calendar what are made in DB, but in FireFox the calendar is empty.. And returned response JSON string is:
[
{"id":"7","title":"Rino","start":"2014-10-22T11:55:46+0300","end":"2014-10-22T11:55:46+0300","url":"nav","allDay":"false"},
{"id":"8","title":"Rin","start":"2014-10-22T13:01:45+0300","end":"2014-10-22T13:01:45+0300","url":"Hello","allDay":"false"},
{"id":"9","title":"Rino","start":"2014-10-23T10:06:22+0300","end":"2014-10-23T10:06:22+0300","url":"Hello","allDay":"false"},
{"id":"10","title":"a","start":"2014-10-23T09:42:04+0300","end":"2014-10-23T09:42:04+0300","url":"a","allDay":"false"},
{"id":"11","title":"1","start":"2014-10-23T09:41:55+0300","end":"2014-10-23T09:41:55+0300","url":"1","allDay":"false"},
{"id":"12","title":"sdas","start":"2014-10-23T10:06:14+0300","end":"2014-10-23T10:06:14+0300","url":"1","allDay":"false"},
{"id":"13","title":"Prju","start":"2014-10-16T00:00:00+0300","end":"2014-10-17T00:00:00+0300","url":"undefined","allDay":"false"}
]
What am I missing, why in the Firefox it doesn't show any event? I have also tried clearing cache etc.. but without any results..

JqGrid Edit Function Not Working But The Parameter is Sent

i have some problem that using jqgrid as jquery framework.
In my case, i have some table which is CRUD function that connect to a table let say departments
in this table there are two id: idms_department, department (name). The idms_department is auto increment column.
here's my jqgrid syntax
$(document).ready(function() {
//alert("start");
jQuery("#departments").jqGrid({
mtype:'GET',
url:'functions/get_dept.php',
editurl:'functions/edit_dept.php',
datatype: "JSON",
colNames:['Department ID','Department'],
colModel:[
{name:'idms_department',index:'idms_department', width:150, editable:false, key:true},
{name:'department',index:'department', width:800,editable:true}
],
loadComplete: function () {
alert("OK");
},
loadError: function (jqXHR, textStatus, errorThrown) {
alert('HTTP status code: ' + jqXHR.status + '\n' +
'textStatus: ' + textStatus + '\n' +
'errorThrown: ' + errorThrown);
alert('HTTP message body (jqXHR.responseText): ' + '\n' + jqXHR.responseText);
},
rowNum:10,
rowList:[5,10,15],
pager: '#pager-departments',
sortname: 'idms_department',
viewrecords: true,
jsonReader: {repeatitems: true, idms_department: "idms_department" },
sortorder: "asc",
caption:"MSC Departments"
});
jQuery("#departments").jqGrid('navGrid','#pager-departments',{edit:true,add:true,del:true},{closeAfterEdit:true},{closeAfterAdd:true},{},{closeAfterSearch:true},{});
jQuery("#departments").jqGrid('gridResize',{minWidth:350,maxWidth:850,minHeight:80, maxHeight:350});
//alert("end");
//start navigation system
$('#navigation-bar').collapsible({
effect: 'none',
initialCollapse: true
});
//end navigation system
});
i can add new data using add dialog in jqgrid, but when i want to edit the form, it doesn't editable.
The problem is the id i think. Before, the editable for idms_department is set to editable:true, the working fine, but when i make it editable:false, because, the user can't add new id himself, so i make it editable:false, and the row is gone from dialog.
I have get response from my firebug, it shows that the function is sending the right data, but, the data is unchanged.
The function of edit php goes here:
if($oper == 'edit'){
$deptid = $_POST['idms_department'];
echo $deptid;
$deptnm = $_POST['department'];
$upt = "UPDATE ms_department SET idms_department = '$deptid', department = '$deptnm' WHERE idms_department = '$deptid'";
if(mysql_query($upt)){
"Edited Successfully";
} else {
die("Error Edit : " .mysql_error());
}
mysql_close();
}
is there anything wrong?
jaGrid send rowid as id, but you use
$deptid = $_POST['idms_department'];
and later WHERE idms_department = '$deptid'" in the UPDATE. You have to change the above statement to
$deptid = $_POST['id'];
or to use prmNames: {id: "idms_department"} option of jqGrid to rename "id" variable which will be sent during editing to "idms_department".

Categories