Pass PHP values to Jquery Calendar - php

I am working on a JQuery event calendar that I would like to populate with multiple values from PHP. I've got a foreach pulling all PHP values needed, but I'm not sure how to properly populate the events array in JQuery with the values that I have PHP gathering.
Thanks in advance for any advice here.
Here is the PHP foreach that gathers all of the event data needed.
<?php foreach ($collection as $content) : ?>
<?php
$eventTitle = $content->getData('title');
$ogDate = $content -> render('mmedia_library_publish_date', array('type' => 'date_short'));
// REFORMAT DATES FROM PHP TO A CALENDAR FRIENDLY FORMAT
$newDate = date('Y-d-m', strtotime($ogDate));
echo $newDate;
?>
<?php endforeach; ?>
Here is the jQuery that populates the calendar, with some dummy events in-place, for reference on the formatting that is needed.
<script type="text/javascript">
require([
'jquery',
'calendar-gc',
'domReady!'
], function ($) {
require(['jquery'],function(e){
var calendar = $("#calendar").calendarGC({
dayBegin: 0,
prevIcon: '<',
nextIcon: '>',
onPrevMonth: function (e) {
console.log("prev");
console.log(e)
},
onNextMonth: function (e) {
console.log("next");
console.log(e)
},
// *********** ADD EVENTS FROM PHP HERE *************
events: [
{
date: new Date("2022-03-15"),
eventName: "EVENT 1",
className: "badge bg-danger",
onclick(e, data) {
console.log(data);
},
dateColor: "red"
},
{
date: new Date("2022-03-20"),
eventName: "EVENT 2",
className: "badge bg-danger",
onclick(e, data) {
console.log(data);
},
dateColor: "red"
},
{
date: new Date("2022-03-22"),
eventName: "EVENT 3",
className: "badge bg-success",
onclick(e, data) {
console.log(data);
},
dateColor: "green"
}
],
onclickDate: function (e, data) {
console.log(e, data);
}
});
})
});
</script>

Not that I recommend this approach but can you try something like
//...
$dateArr = [];
foreach () {
...
$dateArr[] = $newDate;
..
}
echo sprintf('<script>let eventStr = %s;</script>', implode(',', $dateArr));
and then later or at the end of page,
let cal = [];
let dates = eventStr.split(',');
dates.forEach(date => cal.push({
date: new Date(date),
eventName: "EVENT 2",
className: "badge bg-danger",
onclick(e, data) {
console.log(data);
},
dateColor: "red"
})
);
haven't tested it but something like this will make values available on the page and then when you initialize the calendar, you can use that array instead.
var calendar = $("#calendar").calendarGC({
...
...
events: cal,
...
});

Just wanted to post my solution to the original question. The comment/post from Adison Masih pointed me in the right direction (thank you), along with extensive searching, trial and error to get the array to display as needed in jquery.
Hopefully, this will help someone else out there that is looking to perform a similar task.
I ended-up building the array in PHP and format the date with the following code:
<?php $eventData = array(); ?>
<?php
$eventTitle = '<a class="eventCalTitle" href="'.$content->getLinkUrl().'">' .$content->getData('title'). '</a>';
$ogDate = $content -> render('mmedia_library_publish_date', array('type' => 'date_short'));
$newDate = date('Y-m-d', strtotime($ogDate));
$jDate = $newDate;
$tempArray = array("date" => $jDate, "eventName" => $eventTitle, "className" => "badge", "dateColor" => "#006fba");
array_push($eventData, $tempArray)
?>
After the PHP array is created, I then pass the array to jQuery, using json_encode, then further modifying the date objects, adding the new Date() function and then populating the events array with my custom event data:
const jsonData = <?php echo json_encode($eventData); ?>;
$.each(jsonData, function( i, obj ) {
var dateOrig = obj.date;
obj.date = new Date(dateOrig);
});
const option = {
dayBegin: 0,
};
option["events"] = jsonData;
$("#calendar").calendarGC(option)

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]+')');
}
});

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();
}

Fullcalendar using a JSON PHP page as an event source

I am trying to use a PHP page hosted on a MySQL server that generates a JSON feed that I want to use as in the "eventSources" array of Fullcalendar in my Ionic application. The calendar is rendering, but it isn't displaying the dates in the feed. I have been working at this for a couple of days and none of the documents on the Fullcalendar site aren't working.
Here's the JSON String:
{"success":1,"message":"Details Available!","events":[
{"ID":"1","title":"Example Class","start":"2014-08-29 09:00:00","end":"2014-08-29 17:00:00","all_day":"0"},
{"ID":"2","title":"Example Class 2","start":"2014-08-13 00:00:00","end":"2014-08-13 00:00:00","all_day":"0"},
{"ID":"3","title":"Example Event with Time","start":"2014-08-13 12:00:00","end":"2014-08-13 13:00:00","all_day":"0"},
{"ID":"11","title":"Testing 123","start":"2014-08-13 00:00:00","end":"2014-08-13 23:59:00","all_day":"1"}]}
Here is the PHP Page generating the JSON above:
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
header("Content-Type:application/json");
header("Access-Control-Allow-Origin: *");
$user="user";
$pass="password";
$table="database";
$db=new PDO("mysql:host=localhost;dbname=$table", $user,$pass);
//initial query
$query = "Select * FROM table";
//execute query
try {
$stmt = $db->query($query);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt->fetchAll();
if ($rows) {
$response["success"] = 1;
$response["message"] = "Details Available!";
$response["events"] = array();
foreach ($rows as $row) {
$post = array();
$post["ID"] = $row["ID"];
$post["title"] = $row["title"];
$post["start"] = $row["start"];
$post["end"] = $row["end"];
$post["all_day"] = $row["all_day"];
//update our repsonse JSON data
array_push($response["events"], $post);
}
// echoing JSON response
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No Events Available!";
die(json_encode($response));
}
?>
Here is the the controller for the calendar:
App.controller('LogHomeCtrl', function($scope, $log, $state)
{
$scope.TimeTabl = function()
{
$state.go('timetable');
}
});
App.controller('calCtrl', function ($scope, $log, $state)
{
$scope.eventSources = [
{
events: {
url: 'url/calendarConnect.php',
type: 'POST',
error: function() {
alert('there was an error while fetching events!');
},
color: 'yellow', // a non-ajax option
textColor: 'black' // a non-ajax option
}
}
];
});
I have tried using different methods of calling the PHP page, but none of it is working. If someone could point out where I am going wrong that would be great.
Exists few ways how you can set events for calendar:
1.as array:
events: [
{
title: 'Example Class',
start: '2014-08-29 09:00:00',
end: '2014-08-29 17:00:00'
},
{
title: 'Example Class 2',
start: '2014-08-13 00:00:00',
end: '2014-08-13 00:00:00'
}
]
2.as json object:
events: 'url/calendarConnect.php' //must to return json similar to previous example
3.as function:
events: function(start, end, timezone, callback) {
$.ajax({
url: 'url/calendarConnect.php',
dataType: 'json',
success: function(response) {
//get your events from response.events
console.log(response);
}
});
}
4.as custom function:
$.ajax({
url: 'url/calendarConnect.php',
dataType: 'json',
success: function(response) {
//just example
$('.calendar').fullCalendar({
events: response.events
});
}
});
In your case 3-rd way is more appropriate. For more details, please, see official Fullcalendar documentation about events.
Try changing this (add [] after ["events"]):
array_push($response["events"][], $post);

Mark date as booked in fullcalendar

I'm using http://arshaw.com/fullcalendar/ to display a full calendar to show events from a DB via json. I need to mark a date as booked by changing the color of the calender cell.
So im guessing I need something like
If (date == booked){
$(element).css("backgroundColor", "red");
}
Here is the code for populating the calendar.
<script>
$(document).ready(function() {
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: false,
events: {
url: '{{URL::to('/json')}}',
type: 'GET',
},
'': 'h(:mm)t' ,// uppercase H for 24-hour clock
loading: function(bool) {
if (bool) $('#loading').show();
else $('#loading').hide();
}
});
});
Here is my json object
public function json()
{
$bookings = Booking::all();
//dd($bookings);
foreach ($bookings as $b)
$data[] = ['title'=>$b->status,
'start'=> $b->event_date .' ' .$b->start_time,
'end'=>$b->event_date .' ' .$b->end_time,
'description'=>'',
'color'=>'',
'status'=>$b->status,
'backgroundColor' => ($b->status ==='confirmed'?'#FFC0CB' : '#FFA500'),
'slotMinutes'=>'10',
'allDay'=>false];
//return $bookings;
return $data;
}
Ideally I'd like to send an array of dates I need to mark as booked.
If someone can nudge me in the correct direction I'd really appriciated it.
Thanks
this is how I solved it.
eventRender: function (event, element, monthView) {
if (event.title == "booked") {
var date = $.fullCalendar.formatDate( event.start , 'yyyy-MM-dd' );//event.start;
$('.fc-day[data-date="' + date + '"]').addClass('booked');
}
},

flot chart with json data is empty

I need to plot chart in flot with data returned by a php script as json encoded data
i get the data in through jquery like this
$("button").click(function(){
var dp1 = $('#dp1').val();
var dp2 = $('#dp2').val();
$.ajax({
type: "GET",
url: "chart.php",
datatype:"json",
success: onSuccess,
data: {d1:dp1, d2:dp1}
});
function onSuccess(series) {
var plotarea = $("#pieChart");
plotarea.css("height", "300px");
plotarea.css("width", "400px");
$.plot( plotarea , [
{
data: series,
bars: {
show: true
}
}
] );
}
});
the data return is json encoded i can see it in firebug like so
[["ebbok1",39.55],["ebbok2",92.23],["ebbok3",102.44]]
but my chart is empty
the php file returning the json data is
$dataset = array();
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
//echo $row['amount'] . "\t" . $row['product_name']. "\n";
$dataset[] = array( $row['product_name'], $row['amount'] );
}
echo json_encode($dataset,JSON_NUMERIC_CHECK);
what am i doing wrong?
EDIT
i modified my php script, it now returns data like this
[{"label":"ebook1","data":39.55},{"label":"ebook2","data":92.23},{"label":"ebook3","data":102.44}]
but i still get empty chart
Your $.plot call doesn't look correct. You are mixing the options and data together.
var series = [
{"label":"ebbok1","data":12},
{"label":"ebook1","data":27.55},
{"label":"ebook2","data":92.33},
{"label":"ebook3","data":102.44}
];
$.plot( $("#somePlot") , series,
{
series: {
pie: {
show: true
}
}
}
);
See fiddle here.
You've misunderstood how a set of data is expected for flot.
You have:
series = [["label",1],["label2",2],... ];
Flot expects data formatted like this:
series = [[[x1,y1],[x2,y2],...]];// where xN and yN are all NUMBERS
See also the documentation on this topic.
So assuming that you really want to see the labels you've specified, one way to deal with that is to use the ticks property of the xaxis. So you'd return two sets of data:
data = [[[0,1],[1,1],...]];
tickLabels = [[0,"label1"],[1,"label2"],...];
Then in your flot options specify this:
$.plot( plotarea , data, {
series: {
bars: {
show:true;
}
},
xaxis: {
ticks:tickLabels
}
} );
Example: http://jsfiddle.net/ryleyb/8gGEz/1/
EDIT: If you want to keep returning your series data the same way, you can do the manipulation in the javascript:
var tickLabels = [];
for (var i =0;i<series.length;i++){
tickLabels.push([i,series[i][0]);
series[i][0] = i;
}
var data = [series];
//now you can call flot as I described above.
I meet the same problem with you. But now I figure it out.
The problem is cause by your data
[["ebbok1",39.55],["ebbok2",92.23],["ebbok3",102.44]]
It look like what you want to show at x-axis is "category" type.
So flot(v0.8.2) provide 'categories' mode to present the x-axis show what you want as categories.
As following:
Step1: add categories module to your HTML
<script type="text/javascript" src="flot/jquery.flot.categories.js"></script>
Step2: add the following to your js.
var options={
xaxis:{mode: "categories"}
};
try it and enjoy it :)

Categories