jQuery/JS – Outputting objects inside an array – best practice - javascript

Need some advice. I am using a jQuery calendar plugin (which seems to be rare!) and it is completely initialised with JS. No HTML.
To add events, you have to write each event as an object inside an array:
events: [
{
title: "Title of event",
start: {
date: YYYYMMDD or "YYYYMMDD", // "20131230"
time: "HH.MM" // "12.00"
},
end: {
date: YYYYMMDD or "YYYYMMDD", // "20131230"
time: "HH.MM" // "20.00"
}
},
{
title: "Title of event",
start: {
date: YYYYMMDD or "YYYYMMDD", // "20131230"
time: "HH.MM" // "12.00"
},
end: {
date: YYYYMMDD or "YYYYMMDD", // "20131230"
time: "HH.MM" // "20.00"
}
}
],
I am using Django, and would need to write a for loop for each event into this format. So, my question is, what's the best way to do this? JSON? Is this possible? What is best practice to output data as JS objects?
Thanks in advance,
R

As required by #rdck, below is an example how it can be achieved :
Server side (PHP example) :
<?php
$arr = array();
$arr[] = array(
'title'=>'Title of event',
'start' => array(
'date'=>'YYYYMMDD',
'time'=>'HH.MM'
),
'end' => array(
'date'=>'YYYYMMDD',
'time'=>'HH.MM'
),
);
$arr[] = array(
'title'=>'Title of event2',
'start' => array(
'date'=>'YYYYMMDD',
'time'=>'HH.MM'
),
'end' => array(
'date'=>'YYYYMMDD',
'time'=>'HH.MM'
),
);
?>
In HTML
<script type="text/javascript">
var events = '<?php echo json_encode($arr); ?>';
</script>
events is your json object which you can pass directly into your events calendar

I think, best way to do this - is AJAX-request.
But you can add json-string to context-dict and render it in template:
<script type="text/javascript">var events = {{ json_data }};</script>

Related

load Events from database on fullcalendar v6

I'm using FC 6 (upgrading from FC 3). I'm trying to load my events from my MS SQL Server database and JSON file but I don't understand why it's not working.
This is the call I made in my calendar.js:
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
/*CODE*/
events: [{
url: '../script/apps/calendar/load.php',
method: 'POST',
},
{
url: '../../resource/various/vacation.json'
},
{
id: "weekend",
rrule: {
freq: 'weekly',
byweekday: [ 'sa', 'su' ],
dtstart: '2022-01-01',
},
allDay: true,
display:"background",
backgroundColor: "#90ee90"
}
],
But I'm not understanding why I cannot see any events on my calendar.
This is my load.php:
<?php
require_once "../../connection.php";
$data = array();
$query= sqlrsv_query($conn,"SELECT * FROM gestioneOre ORDER BY idAssenza");
while($result = sqlrsv_fetch_array($query)){
$data[] = array(
'idAssenza' => $result['idAssenza'],
'title' => $result['ename'],
'start' => $result['starts'],
'end' => $result['ends'],
'nomeUtente'=> $result['nomeUtente'],
'pausaPranzo'=> $result['pausaPranzo']
);
}
echo json_encode($data);
?>
I change by myself the JSON with an old one I had and now it's working again; but now i'ts not loading the weekends and the one from the database.
JSON send it from my database ->

Fullcalendar - Problem with JSON DATA from External File

I would like to pull some events from the database. But first of all, one would be enough. I don´t know whats wrong cause i dont get any error messages...
JS:
$(document).ready(function() {
$('#calendar').fullCalendar({
locale: 'de',
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
events: 'example.org/termine/PartnerTermine/&id=Xsdfeecvsdfgerger}'
});
});
If i am goin to call my events url, the answer is:
{"title":"Termin 1","start":"1575675560"}
And also, when i´m going to array it to
[{"title":"Termin 1","start":"1575675560"}]
the Event wont be showed, i dont know why.
The other php-file:
$meine_termine = array( // OR $meine_termine[] = array( - both doesnt work.
"title" => 'Termin 1',
"start" => '1575675560'
);
$json_termine = json_encode($meine_termine);
echo $json_termine;
exit;
The question is:
What is wrong and why doenst it pull the event from my file...
thanks a lot in advance.
Andre
Question closed, found a solution.
JS-Side:
eventSources: [
// your event source
{
url: 'https://example.org/termine/PartnerTermine/&id=hash_id',
type: 'POST',
data: {
custom_param1: 'something',
custom_param2: 'somethingelse'
},
error: function() {
alert('there was an error while fetching events!');
}
}
]
php-side:
foreach ($termine AS $termin)
{
$meine_termine[] = array(
"allDay" => "",
"title" => $termin['title'],
"id" => $termin['title'],
"end" => "",
"start" => $termin['datum']
);
}
$json_termine = json_encode($meine_termine);
echo ($json_termine);
exit;
The Fields for the calendar has to be id, title, allday,end,start. works fine if the json will be echo'ed.

show event in fullcalendar with json.parse (SyntaxError: missing : after property id)

Show events in the calendar after the loading screen.
events: {
JSON.parse(get_data());
},
CONTROLLER all is ok no problem here expept for the JSON.PARSE
$calendar = array();
foreach($data_calendar as $key => $val) {
$calendar[] = array(
'id' => intval($val - > id),
'title' => $val - > title,
'description' => trim($val - > description),
'start' => date_format(date_create($val - > start_date), "Y-m-d H:i:s"),
'end' => date_format(date_create($val - > end_date), "Y-m-d H:i:s"),
'color' => $val - > color,
);
}
$data = array();
$data['get_data'] = json_encode($calendar);
$data['telaativa'] = 'agenda'; //retorna agenda penso que manté menu barra esquerda colapsada em agenda
$data['tela'] = ('/calendario/view_agenda--');
view_agenda--
$this - > load - > view('view_home2', $data);
RESULT id with 1 or "1" in the result is because i declare intval for id so i can get both formats in output.
'get_data' => string '[{"id":1,
'get_data' => string '[{"id":"1",
array (size=3)
'get_data' => string '[{"id":1,"title":"teste evento1","description":"descri\u00e7\u00e3o do evento bla bla bla","start":"2019-05-06 00:00:00","end":"2019-05-07 00:00:00","color":"#0071c5"},{"id":6,"title":"cert soldador 1-1","description":"descrtivo do certificado ser 111 bw t1-25mm s275","start":"2019-05-29 23:00:00","end":"2019-05-30 00:00:00","color":"#40E0D0"},{"id":7,"title":"cert soldador 1-2 soldador nr1","description":"certificado de soldador nr 1 doc 1-2","start":"2019-05-30 00:00:00","end":"2019-05-31 00:00:00","color'... (length=5865)
'telaativa' => string 'agenda' (length=6)
'tela' => string '/calendario/view_agenda--' (length=25)
VIEW
$(document).ready(function() {
$('.date-picker').datepicker();
$('#calendarIO').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay'
},
defaultDate: moment().format('YYYY-MM-DD'),
editable: true,
eventLimit: true, // allow "more" link when too many events
selectable: true,
selectHelper: true,
select: function(start, end) {
$('#create_modal input[name=start_date]').val(moment(start).format('YYYY-MM-DD'));
$('#create_modal input[name=end_date]').val(moment(end).format('YYYY-MM-DD'));
$('#create_modal').modal('show');
save();
$('#calendarIO').fullCalendar('unselect');
},
eventDrop: function(event, delta, revertFunc) { // si changement de position
editDropResize(event);
},
eventResize: function(event, dayDelta, minuteDelta, revertFunc) { // si changement de longueur
editDropResize(event);
},
eventClick: function(event, element) {
deteil(event);
editData(event);
deleteData(event);
},
events: {
JSON.parse(get_data());
},
});
});
ERROR
SyntaxError: missing : after property id
If i delete JSON.parse(get_data()); my calendar will be visible but no events. If I add an event it will be shown until I refresh the page. All function work expect loading data from DB into the calendar.
You seem to be confused about how to use your PHP view data in your view.
I think maybe you should read this: https://www.codeigniter.com/user_guide/general/views.html#adding-dynamic-data-to-the-view . It shows you how to inject the PHP data you provided to the view into your page.
What you're doing now is writing pure JavaScript which tries to call a function which doesn't exist. What you need to do is write a PHP snippet to inject the server-side data into the HTML and JavaScript code which the PHP is creating.
I'm not a CodeIgniter expert, but based on that documentation page, what I think you should be writing is:
events: <?php echo $get_data; ?>,
If you inject it like this without quote marks, then it will be automatically treated as JavaScript array literal, so there's no need for JSON.parse(). This works because JSON syntax is a subset of valid JavaScript object syntax. If you use the View Source feature in your browser to view the finished output of your page, you'll see what I mean.
(Note that you also need to remove the { and } from the events: declaration, because fullCalendar expects an array, not an object.

Add php to js file

I am working on a USA map with states to show which states have available properties by changing the color of the state.
I am using Leaflet for the map and have used the Interactive Choropleth Map (https://leafletjs.com/examples/choropleth/) as a basis to build this.
I have added "availability":"2" to the us-states.js file, this is where the number of properties will be shown. I would like to insert a php query
into the .js file to pull the number of properties for that state. Here is a sample from the us-states.js file so that you can see the layout:
{"type":"Feature","id":"02","properties":{"name":"North Carolina","availability":"2"},"geometry":{"type":"MultiPolygon","coordinates":[[[[-131.602021,55.117982],
And I am using this to change color:
// get color depending on population density value
function getColor(d) {
return d > 1 ? '#e1cb7f' :
'#173e34';
}
function style(feature) {
return {
weight: 2,
opacity: 1,
color: 'white',
dashArray: '',
fillOpacity: 1.9,
fillColor: getColor(feature.properties.availability)
};
}
This is my php query:
<?php $count = array('post_type' => 'property', 'meta_key' => 'state', 'meta_value' => 'NC'); $myquery = new WP_Query($count); ?>
and I have tried to add this to the js file, but it will not work:
"availability":"<?php echo json_encode($myquery->found_posts) ?>"
If I manually add the number of properties to the us-states.js file the color does change on the map, so the color change part is working, I just cannot get the php to work in the .js file.
Here is my webpage: https://www.thekeithcorp.com/interactive-map/
Any help would be appreciated!
What you are looking for is wp_localize_script
Execute the query
Register the script using wp_register_script
Localize the registered script with the result of the query using wp_localize_script
Enqueue the script using wp_enqueue_script which references the JavaScript array that WordPress adds before the registered script
on WordPress, can pass variables to JS, eg. with the theme's functions.php:
function localize() {
$items = WP_Query ...
wp_register_script( 'custom', get_template_directory_uri() . '/js/scripts.js', array('jquery'), false, true );
$script_vars = ["features" => []];
for($i=0; $i < $items.size(); $i++) {
array_push($script_vars['features'], (object) array(
"id" => 2,
"type" => "Feature",
"properties" => (object) array(
"name" => "North Carolina",
"availability"=> 2
),
"geometry" => (object) array(
"type" => "MultiPolygon",
"coordinates"=> [ ... ]
)
));
}
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'custom' );
wp_localize_script('custom', 'script_vars', $script_vars);
}
if( !is_admin()) {
add_action("wp_enqueue_scripts", "localize", 10);
}
while you just could change the file-name suffix from .js to .php ...however, when integrating the map with WordPress posts, it's better to localize or to use WP AJAX for loading the data asynchronously - or even cache the HTML output, which may not change that much, except when something is being added.
I got this to work using this in the functions file:
wp_register_script( 'scount', get_template_directory_uri() . '/assets/js/us-states.js' );
// Localize the script with our data that we want to use
$args = array(
'post_type' => 'property',
'fields' => 'ids',
'meta_query' => array(
array(
'key' => 'state',
'value' => 'NC'
)
)
);
$results = new WP_Query($args);
$completed = count($results->posts);
wp_localize_script( 'scount', 'completed', $completed );
// The script can be enqueued now or later.
wp_enqueue_script( 'scount' );
And using this in the json file:
( JSON.stringify(completed) )}
Note there is no ";" at the end!

TinyMCE Dynamic Buttons/Methods

I'm attempting to create a Wordpress plugin which allows you to easily add a dropdown menu with items in for inserting shortcodes. To do this, I need to 'hook' into TinyMCE, registering a custom plugin. My plan is to allow users to setup the shortcode menu items using a simple PHP array.
The following class is instantiated which registers a new button and the plugin script:
<?php
namespace PaperMoon\ShortcodeButtons;
defined('ABSPATH') or die('Access Denied');
class TinyMce {
public function __construct()
{
$this->add_actions();
$this->add_filters();
}
private function add_actions()
{
add_action('admin_head', [$this, 'print_config']);
}
public function print_config()
{
$shortcodes_config = include PMSB_PLUGIN_PATH . 'lib/shortcodes-config.php'; ?>
<script type='text/javascript' id="test">
var pmsb = {
'config': <?php echo json_encode($shortcodes_config); ?>
};
</script> <?php
}
private function add_filters()
{
add_filter('mce_buttons', [$this, 'register_buttons']);
add_filter('mce_external_plugins', [$this, 'register_plugins']);
}
public function register_buttons($buttons)
{
array_push($buttons, 'shortcodebuttons');
return $buttons;
}
public function register_plugins($plugin_array)
{
$plugin_array['shortcodebuttons'] = PMSB_PLUGIN_URL . 'assets/js/tinymce.shortcodebuttons.js';
return $plugin_array;
}
}
A user would create a PHP array like so (which is included in the above class and output as a javascript variable in the header):
<?php
return [
[
'title' => 'Test Shortcode',
'slug' => 'text_shortcode',
'fields' => [
'type' => 'text',
'name' => 'textboxName',
'label' => 'Text',
'value' => '30'
]
],
[
'title' => 'Test Shortcode2',
'slug' => 'text_shortcode2',
'fields' => [
'type' => 'text',
'name' => 'textboxName2',
'label' => 'Text2',
'value' => '30'
]
]
];
Finally, here's the actual plugin script:
"use strict";
(function() {
tinymce.PluginManager.add('shortcodebuttons', function(editor, url) {
var menu = [];
var open_dialog = function(i)
{
console.log(pmsb.config[i]);
editor.windowManager.open({
title: pmsb.config[i].title,
body: pmsb.config[i].fields,
onsubmit: function(e) {
editor.insertContent('[' + pmsb.config[i].slug + ' textbox="' + e.data.textboxName + '" multiline="' + e.data.multilineName + '" listbox="' + e.data.listboxName + '"]');
}
});
}
for(let i = 0; i <= pmsb.config.length - 1; i++) {
menu[i] = {
text: pmsb.config[i].title,
onclick: function() {
open_dialog(i)
}
}
}
console.log(menu);
editor.addButton('shortcodebuttons', {
text: 'Shortcodes',
icon: false,
type: 'menubutton',
menu: menu
});
});
})();
The button registers fine, the menu items also register fine but when it comes to click on to open up a modal window, I get this error:
Uncaught Error: Could not find control by type: text
I think it's something to do with the fact that the 'fields' is coming from a function which, for some reason, TinyMCE doesn't like - even though it's built correctly.
I had thought of doing this a different way - by creating a PHP file which outputs the correct JS but if I do that, I can't register it as a TinyMCE plugin when using the mce_external_plugins action hook.
I found another question which ran in to the same problem with no answer.
I've really hit a wall with this one, any help would be hugely appreciated!
Well, the typical thing happened - as soon as I post the question, I stumble upon the answer. Maybe I need to get myself a rubber desk duck?
Anyway, the clue is in the error message. Despite having looked at quite a number of tutorials which all suggest using 'text' as the control type, it's actually 'textbox'. I'm guessing this is a more recent change in TinyMCE and the tutorials I was looking at were a bit older.
I searched for yet another tutorial and found the answer staring me right in the face.

Categories