Adding different hyperlink yo php fullcalendar master plugin - php

Differs to the full calendar master database, I added a column called "link" in the event table of the database. My purpose is to allow users to go to different links when they click corresponding day.
I observe other posts/ documentation, still cannot figure out the solution.
Can someone help me?Below is the code of event.php and my js part in the index.html. I do not change any part of other files of the plugin
$json = array();
$request = "SELECT * FROM events ORDER BY id";
try {
$bdd = new PDO('mysql:host=localhost;dbname=test', 'root', '');
} catch (Exception $e) {
exit('Unable to connect to database.');
}
$result = $bdd->query($request) or die(print_r($bdd->errorInfo()));
echo json_encode($result->fetchAll(PDO::FETCH_ASSOC));
$(document).ready(function() {
function fmt(date) {
return date.format("YYYY-MM-DD HH:mm");
}
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var calendar = $('#calendar').fullCalendar({
editable: true,
header: {
left: 'prev,next',
center: 'title',
right: '',
},
events: "events.php",
eventRender: function(event, element, view) {
if (event.allDay === 'true') {
event.allDay = true;
} else {
event.allDay = false;
}
},
selectable: true,
selectHelper: true,
editable: true,
select: function(start, end, jsEvent, view) {
window.location = "I need different links fetched from db!!"
},
});
});

Related

Google map API Shows Blank Screen in my Laravel Application

In my Laravel Application i use google map to Display Route and Distance Between Two Places. after setting google map, i test my app. its display as Blank Screen. I even registered the application using a key that I applied for on Google's website. I have been working on this for 2 hours and cannot figure it out.
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=MY API KEY&libraries=places&callback=initMap&sensor=false" async defer></script>
<script type="text/javascript">
function GetRoute() {
source = document.getElementById("pickupaddress").value;
destination = document.getElementById("deliveryaddress").value;
var request = {
origin: source,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING
};
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [source],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function (response, status) {
if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
var distance = response.rows[0].elements[0].distance.text;
var dvDistance = document.getElementById("distanceops");
dvDistance.innerHTML = "";
dvDistance.innerHTML += distance;
} else {
alert("Unable to find the distance via road.");
}
});
}
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
mapTypeControl: false,
center: {lat: 4.2105, lng: 101.9758},
zoom: 8
});
new AutocompleteDirectionsHandler(map);
}
/**
* #constructor
*/
function AutocompleteDirectionsHandler(map) {
this.map = map;
this.originPlaceId = null;
this.destinationPlaceId = null;
this.travelMode = 'WALKING';
var originInput = document.getElementById('pickupaddress');
var destinationInput = document.getElementById('deliveryaddress');
this.directionsService = new google.maps.DirectionsService;
this.directionsDisplay = new google.maps.DirectionsRenderer;
this.directionsDisplay.setMap(map);
var deliveryrestrictOptions = {componentRestrictions: {country: 'my'},placeIdOnly: true};
var originAutocomplete = new google.maps.places.Autocomplete(
originInput, deliveryrestrictOptions);
var destinationAutocomplete = new google.maps.places.Autocomplete(
destinationInput,deliveryrestrictOptions);
this.setupPlaceChangedListener(originAutocomplete, 'ORIG');
this.setupPlaceChangedListener(destinationAutocomplete, 'DEST');
}
// Sets a listener on a radio button to change the filter type on Places
// Autocomplete.
AutocompleteDirectionsHandler.prototype.setupClickListener = function(id, mode) {
var radioButton = document.getElementById(id);
var me = this;
radioButton.addEventListener('click', function() {
me.travelMode = mode;
me.route();
});
};
AutocompleteDirectionsHandler.prototype.setupPlaceChangedListener = function(autocomplete, mode) {
var me = this;
autocomplete.bindTo('bounds', this.map);
autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
if (!place.place_id) {
window.alert("Please select an option from the dropdown list.");
return;
}
if (mode === 'ORIG') {
me.originPlaceId = place.place_id;
} else {
me.destinationPlaceId = place.place_id;
}
me.route();
});
};
AutocompleteDirectionsHandler.prototype.route = function() {
if (!this.originPlaceId || !this.destinationPlaceId) {
return;
}
var me = this;
this.directionsService.route({
origin: {'placeId': this.originPlaceId},
destination: {'placeId': this.destinationPlaceId},
travelMode: this.travelMode
}, function(response, status) {
if (status === 'OK') {
me.directionsDisplay.setDirections(response);
GetRoute();
} else {
window.alert('Directions request failed due to ' + status);
}
});
};
window.ParsleyConfig = {
errorsWrapper: '<div></div>',
errorTemplate: '<span class="error-text"></span>',
classHandler: function (el) {
return el.$element.closest('input');
},
successClass: 'valid',
errorClass: 'invalid'
};
</script>
I have worked on google maps. Google maps won't load inside a modal or any hidden divs (for perf reasons).
Here is what you do. Trigger resize on the map and it should render the map.
google.maps.event.trigger(map, 'resize') where map is your map instance name.

How to add a layer in openlayer3 using ajax?

I am new to Openlayers3.....I am trying to load data from database using ajax & php to load vector data to openlayers3,I am stuck and don't know what is the problem.
here is my code
Can anyone help me in that?
$(document).ready(function()
{
//extent of the map
view = new ol.View({
center:ol.proj.transform([125.7799,8.7965], 'EPSG:4326', 'EPSG:3857'),
zoom:11,
maxZoom:18,
minZoom:2
});
//BaseLayer
var baseLayer = new ol.layer.Tile({
source: new ol.source.OSM()
});
// create a vector source that loads a GeoJSON file
var vectorSource = new ol.source.Vector({
projection: 'EPSG:4326',
url: 'data/Boundaries.geojson',
format: new ol.format.GeoJSON()
});
var geoJSONFormat = new ol.format.GeoJSON();
var farmersSource = new ol.source.Vector({
loader: function(extent, resolution, projection) {
var url = 'allfarmers_geojson.php?p=' + extent.join(',');
$.ajax({
url: url,
success: function(data) {
var features = geoJSONFormat.readFeatures(data);
farmersSource.addFeatures(features);
}
});
},
strategy: ol.loadingstrategy.bbox
});
// Polygons
var createPolygonStyleFunction = function() {
return function(feature, resolution) {
var style = new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'blue',
width: 1
}),
fill: new ol.style.Fill({
color: '#faeaac'
}),
//text: createTextStyle(feature)
});
return [style];
};
};
// a vector layer to render the source
var vectorLayer = new ol.layer.Vector({
source: vectorSource,
style:createPolygonStyleFunction()
});
var farmersLayer = new ol.layer.Vector({
source: farmersSource
//style:createPolygonStyleFunction()
});
//Map
var map = new ol.Map({
target:'map',
controls:ol.control.defaults().extend([
new ol.control.ScaleLine(),
new ol.control.ZoomSlider()
]),
renderer: 'canvas',
layers:[baseLayer,vectorLayer,farmersLayer],
view:view
});
//////////styling features and with mouse over color change/////////////
var highlightStyleCache = {};
var featureOverlay = new ol.layer.Vector({
source: new ol.source.Vector(),
map: map,
style: function(feature, resolution) {
var text = resolution < 5000 ? feature.get('NAME_3') : '';
if (!highlightStyleCache[text]) {
highlightStyleCache[text] = new ol.style.Style({
stroke: new ol.style.Stroke({
color: '#f00',
width: 1
}),
fill: new ol.style.Fill({
color: 'rgba(255,0,0,0.1)'
}),
text: new ol.style.Text({
font: '12px Calibri,sans-serif',
text: text,
fill: new ol.style.Fill({
color: '#f00'
})
})
});
}
return highlightStyleCache[text];
}
});
var highlight;
var displayFeatureInfo = function(pixel) {
var feature = map.forEachFeatureAtPixel(pixel, function(feature) {
return feature;
});
if (feature !== highlight) {
if (highlight) {
featureOverlay.getSource().removeFeature(highlight);
}
if (feature) {
featureOverlay.getSource().addFeature(feature);
}
highlight = feature;
}
};
map.on('pointermove', function(evt) {
if (evt.dragging) {
return;
}
var pixel = map.getEventPixel(evt.originalEvent);
displayFeatureInfo(pixel);
});
map.on('click', function(evt) {
displayFeatureInfo(evt.pixel);
});
//////////End of styling features and with mouse over color change/////////////
});
and here is my php file
<?php
$conn = new PDO('mysql:host=localhost;dbname=FarmersDB','root','admin');
$sql = 'SELECT *, _coordinates__latitude AS x, _coordinates__longitude AS y FROM farmers';
if (isset($_GET['bbox']) || isset($_POST['bbox'])) {
$bbox = explode(',', $_GET['bbox']);
$sql = $sql . ' WHERE x <= ' . $bbox[2] . ' AND x >= ' . $bbox[0] . ' AND y <= ' . $bbox[3] . ' AND y >= ' . $bbox[1];
}
$rs = $conn->query($sql);
if (!$rs) {
echo 'An SQL error occured.\n';
exit;
}
$geojson = array(
'type' => 'FeatureCollection',
'features' => array()
);
while ($row = $rs->fetch(PDO::FETCH_ASSOC)) {
$properties = $row;
unset($properties['x']);
unset($properties['y']);
$feature = array(
'type' => 'Feature',
'geometry' => array(
'type' => 'Point',
'coordinates' => array(
$row['x'],
$row['y']
)
),
'properties' => $properties
);
array_push($geojson['features'], $feature);
}
header('Content-type: application/json');
echo json_encode($geojson, JSON_NUMERIC_CHECK);
$conn = NULL;
?>
No exactly sure what problem you're having but try this..You probably need to set the right projection and parse the data response from the server..Projection is EPSG:3857 by default:
success: function(data) {
var JSONData;
try {
JSONData = JSON.parse(data);
} catch(err) {
alert(err);
return;
}
var format = new ol.format.GeoJSON();
var features = format.readFeatures(JSONData, {
featureProjection: 'EPSG:3857'
});
farmersSource.addFeatures(features);
farmersSource.changed();
}
});
Also, on var vectorSource change the project to EPSG:3857. Another thing, you need to add the vectorloader property to you source.vector. For example:
var locationSource = new ol.source.Vector({
url: loc_url,
format: new ol.format.GeoJSON({
defaultDataProjection :'EPSG:3857'
}),
loader: vectorLoader,
strategy: ol.loadingstrategy.all
});
The vectorLoader function looks like this and makes your ajax calls to the server. Special note on loader functions - When clear() is called on the source layer, it will trigger the vector loader function again:
var vectorLoader = function(extent, resolution, projection) {
var url = this.getUrl();
utils.refreshGeoJson(this);
}
var utils = {
refreshGeoJson: function(source,url) {
var now = Date.now();
if (typeof url == 'undefined') {
url = source.getUrl();
}
url += '?t=' + now; //Prevents browser caching if retrieving a geoJSON file
console.info('refreshGeoJson url: ' + url);
this.getJson(url).when({
ready: function(response) {
var JSONResponse;
try {
JSONResponse = JSON.parse(response);
} catch(err) {
alert(err + ' - ' + url);
return;
}
var format = new ol.format.GeoJSON();
var features = format.readFeatures(JSONResponse, {
featureProjection: 'EPSG:3857'
});
source.addFeatures(features);
source.changed();
}
});
},
getJson: function(url) {
var xhr = new XMLHttpRequest(),
when = {},
onload = function() {
console.log(url + ' xhr.status: ' + xhr.status);
if (xhr.status === 200) {
console.log('getJson() xhr: ');
console.dir(xhr);
console.log('getJson() xhr.response: ');
console.dir(xhr.response);
when.ready.call(undefined, xhr.response);
}
if (xhr.status === 404) {
console.log('map file not found! url: ' + url);
}
},
onerror = function() {
console.info('Cannot XHR ' + JSON.stringify(url));
};
xhr.open('GET', url, true);
xhr.setRequestHeader('cache-control', 'no-store');
xhr.onload = onload;
xhr.onerror = onerror;
xhr.send(null);
return {
when: function(obj) { when.ready = obj.ready; }
};
}
};
Threw in a lot of extras here because I'm not sure what your problem is with your code. The example above work great for me retrieving geoJSON files from the server that are periodically changed..It should work the same for you if calling a PHP script, just make sure that the script returns geoJSON data according to this spec: http://geojson.org/geojson-spec.html

Need to change event background and opacity in FullCalendar

As a follow up to Display image as background in fullcalendar, I now have a fully working MySQL solution, but I cannot find a way to change the background if a custom column that I set in my database is not empty (picture), nor changing the same opacity according to the same condition.
In my other question, I was able to change the background in dayRender and the opacity in eventRender:
dayRender: function (date, cell) {
cell.css("background","url(https://www.mozilla.org/media/img/firefox/firefox-256.e2c1fc556816.jpg) no-repeat center");
cell.css("background-size","contain")
},
eventRender: function(event, element) {
$(element).css("opacity", "0.75");
}
});
Now my js code looks like this:
$(document).ready(function() {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var calendar = $('#calendar').fullCalendar({
editable: true,
header: {
left: 'prev,next today',
center: 'title',
right: 'month'
},
events: "/events.php",
dayRender: function (date, cell, view) {
cell.css("background","url(https://www.mozilla.org/media/img/firefox/firefox-256.e2c1fc556816.jpg) no-repeat center");
cell.css("background-size","contain")
},
eventRender: function(event, element) {
}
});
})
The PHP page to get the event data from the MySQL database is:
<?php
// List of events
$json = array();
// Query that retrieves events
$requete = "SELECT * FROM evenement ORDER BY id";
// connection to the database
try {
$bdd = new PDO('mysql:host=localhost;dbname=HIDDEN', 'HIDDEN', 'HIDDEN');
} catch(Exception $e) {
exit('Unable to connect to database.');
}
// Execute the query
$resultat = $bdd->query($requete) or die(print_r($bdd->errorInfo()));
// sending the encoded result to success page
echo json_encode($resultat->fetchAll(PDO::FETCH_ASSOC));
?>
I tried to use this in dayRender to change the background with no success so far:
var eventoObj = $("#calendar").fullCalendar( 'clientEvents')[0];
alert(eventoObj.picture_url)
Can anyone help me out figuring this out?
Thank you for your time and help.

Issue of CORS. I already add header in serverside

currently i am create a small that display markers on google map. Coordinates come from mysql database but i getting the error i don't know why it's came.
ERRor - XMLHttpRequest cannot load http://localhost:8080/markers.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.1.7:8100' is therefore not allowed access. The response had HTTP status code 404.
markers.php
<?php
//Create a connection to the database
$mysqli = new mysqli("localhost", "test");
if (!$mysqli) {
die("Connection failed: " . mysqli_connect_error());
}
//The default result to be output to the browser
$result = "{'success':false}";
//Select everything from the table containing the marker informaton
$query = "SELECT * FROM marker";
//Run the query
$dbresult = $mysqli->query($query);
//Build an array of markers from the result set
$markers = array();
while($row = $dbresult->fetch_array(MYSQLI_ASSOC)){
$markers[] = array(
'id' => $row['id'],
'name' => $row['name'],
'lat' => $row['lat'],
'lng' => $row['lng']
);
}
//If the query was executed successfully, create a JSON string containing the marker information
if($dbresult){
$result = "{'success':true, 'markers':" . json_encode($markers) . "}";
}
else
{
$result = "{'success':false}";
}
//Set these headers to avoid any issues with cross origin resource sharing issues
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type,x-prototype-version,x-requested-with');
//Output the result to the browser so that our Ionic application can see the data
echo($result);
?>
app.js
angular.module('starter', ['ionic', 'ngCordova'])
.run(function($ionicPlatform, GoogleMaps) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if(window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
GoogleMaps.init();
})
})
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('map', {
url: '/',
templateUrl: 'templates/map.html',
controller: 'MapCtrl'
});
$urlRouterProvider.otherwise("/");
})
.factory('Markers', function($http) {
var markers = [];
return {
getMarkers: function(){
return $http.get("http://localhost:8080/markers.php").then(function(response){
markers = response;
return markers;
});
}
}
})
.factory('GoogleMaps', function($cordovaGeolocation, Markers){
var apiKey = false;
var map = null;
function initMap(){
var options = {timeout: 10000, enableHighAccuracy: true};
$cordovaGeolocation.getCurrentPosition(options).then(function(position){
var latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var mapOptions = {
center: latLng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);
//Wait until the map is loaded
google.maps.event.addListenerOnce(map, 'idle', function(){
//Load the markers
loadMarkers();
});
}, function(error){
console.log("Could not get location");
//Load the markers
loadMarkers();
});
}
function loadMarkers(){
//Get all of the markers from our Markers factory
Markers.getMarkers().then(function(markers){
console.log("Markers: ", markers);
var records = markers.data.markers;
for (var i = 0; i < records.length; i++) {
var record = records[i];
var markerPos = new google.maps.LatLng(record.lat, record.lng);
// Add the markerto the map
var marker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: markerPos
});
var infoWindowContent = "<h4>" + record.name + "</h4>";
addInfoWindow(marker, infoWindowContent, record);
}
});
}
function addInfoWindow(marker, message, record) {
var infoWindow = new google.maps.InfoWindow({
content: message
});
google.maps.event.addListener(marker, 'click', function () {
infoWindow.open(map, marker);
});
}
return {
init: function(){
initMap();
}
}
})
.controller('MapCtrl', function($scope, $state, $cordovaGeolocation) {
});
There is a configuration to do with Ionic :
http://ionicframework.com/docs/cli/test.html
Or if you are using google chrome you can add this plugin, it solve the problem for me :
https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi
Hope it should help you

fullcalendar not show a events with codeigniter

I'm trying to make a calendar with "FullCalendar" and codeigniter. I have read several questions on this page, but still do not understand because the calendar does not show me the events.
I have this routes:
$route['calendar'] = 'user/calendar/showCalendar';
$route['calendar/events'] = 'user/calendar/getEvents';
This is the controller:
public function showCalendar()
{
$this->template->add_css(base_url() . 'assets/plugins/fullcalendar/fullcalendar.min.css');
$this->template->add_js('https://code.jquery.com/ui/1.11.1/jquery-ui.min.js');
$this->template->add_js('https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.7.0/moment.min.js');
$this->template->add_js(base_url() . 'assets/plugins/fullcalendar/fullcalendar.min.js');
$this->template->add_js(base_url() . 'assets/plugins/fullcalendar/config.js');
$data = array();
$this->template->write('title', 'Calendar', TRUE);
$this->template->write_view('header', 'user/template/header');
$this->template->write_view('sidebar', 'user/template/sidebar');
$this->template->write_view('content', 'user/calendar/calendar', $data, TRUE);
$this->template->render();
}
public function getEvents()
{
if($this->input->is_ajax_request())
{
$events = $this->calendar_mdl->getEvents();
echo json_encode($events);
}
}
My config.js:
$(function () {
/* initialize the external events
-----------------------------------------------------------------*/
function ini_events(ele) {
ele.each(function () {
// create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/)
// it doesn't need to have a start or end
var eventObject = {
title: $.trim($(this).text()) // use the element's text as the event title
};
// store the Event Object in the DOM element so we can get to it later
$(this).data('eventObject', eventObject);
// make the event draggable using jQuery UI
$(this).draggable({
zIndex: 1070,
revert: true, // will cause the event to go back to its
revertDuration: 0 // original position after the drag
});
});
}
ini_events($('#external-events div.external-event'));
/* initialize the calendar
-----------------------------------------------------------------*/
//Date for the calendar events (dummy data)
var date = new Date();
var d = date.getDate(),
m = date.getMonth(),
y = date.getFullYear();
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
buttonText: {
today: 'hoy',
month: 'mes',
week: 'semana',
day: 'dia'
},
//Random default events
editable: true,
events: "http://project.dev/calendar/events"
});
});
And my model:
public function getEvents()
{
$this->db->select('*');
$this->db->order_by('id', 'DESC');
$query = $this->db_get(dbCalendar); // dbCalendar is a constant
if($query->num_rows() > 0)
{
return $query->result_array();
}
return FALSE;
}
It is the first time I try to use fullCalnedar, and I do not understand why it don't show me my events. I read the documentation, but don't it did not helped me to find out what the error may be.

Categories