fullcalendar php global variable to external JS file - javascript

I'm trying to pass a global PHP variable to an external JS file for use with fullcalendar 3.1. Basically I want to allow the user to specify the start and the end time of the agendaDay. The agendaDay works perfectly fine if I manually define the hours such as 09:00:00, but I want the user to decide what time to start and end their business day.
index.php
$begin = "09:00:00"; // will become global variables.
$end = "17:00:00";
?>
<script>
var begin = '<?php echo $begin?>';
var end= '<?php echo $end?>';
</script>
<link href="css/fullcalendar.css" rel="stylesheet" />
<link href="css/fullcalendar.print.css" rel="stylesheet" media="print" />
<script src="js/moment.min.js"></script>
<script src="js/fullcalendar.js"></script>
fullcalendar.js
var AGENDA_ALL_DAY_EVENT_LIMIT = 5;
var begin=$('#begin').val();
var end=$('#end').val();
// potential nice values for the slot-duration and interval-duration
// from largest to smallest
var AGENDA_STOCK_SUB_DURATIONS = [
{ hours: 1 },
{ minutes: 30 },
{ minutes: 15 },
{ seconds: 30 },
{ seconds: 15 }
];
fcViews.agenda = {
'class': AgendaView,
defaults: {
allDaySlot: true,
slotDuration: '00:30:00',
minTime: + begin,
maxTime: '22:00:00',
slotEventOverlap: true // a bad name. confused with overlap/constraint system
}
};
How can I get the variables start and end to in my fullcalendar.js file? Can someone show me the JS code needed for that please? Thanks in advance.

In index.php:
<script>
var begin = '<?php echo $begin?>';
var end= '<?php echo $end?>';
</script>
this will set the two variables globally, so both of them will be available in all js files loaded.
You can test this by doing a dump in fullcalendar.js on first line:
console.log('begin: '+begin+ ' end: '+end); // you should see the values from php
but doing this using jQuery:
var begin=$('#begin').val();
var end=$('#end').val();
you will override the two variables with the output of jQuery selection.
A thing that will help is to do the dump at first line, and after this assignation.
console.log('begin: '+begin+ ' end: '+end);
var AGENDA_ALL_DAY_EVENT_LIMIT = 5;
var begin=$('#begin').val();
var end=$('#end').val();
console.log('begin: '+begin+ ' end: '+end);
This jQuery selection will search for inputs with id "begin" and "and" trying to get their values.
I suppose you have this inputs, for user to change them, so you should set the initial values, from php to them and your script will work:
<input type="text" id="begin" value="<?php echo $begin?>" />
<input type="text" id="end" value="<?php echo $end?>" />
If values $begin and $end are static and you do not have the inputs, you should remove the jQuery selection, this two lines, and script will work:
var begin=$('#begin').val();
var end=$('#end').val();

Related

Call function which was load in footer

In a php foreach, I would convert a date using the client timezone.
Actually, it doesn't work:
<html>
<body>
<?php foreach ($topic as $post) { ?>
<span id="date">
<script type='text/javascript'>
document.write(window.date('<?php echo $date;?>'));
</script>
</span>
<?php } ?>
<script type='text/javascript'>
function date(VarDate) {
var b = VarDate.split(/[: ]/g);
var m = {jan:0, feb:1, mar:2, apr:3, may:4, jun:5, jul:6, aug:7, sep:8, oct:9, nov:10, dec:11};
var isoTime = Date.UTC(b[7], m[b[1].toLowerCase()], b[2], b[3], b[4], b[5]);
var date = new Date(isoTime).toLocaleDateString(navigator.language, {day: '2-digit', month:'2-digit', year:'2-digit'});
var time = new Date(isoTime).toLocaleTimeString(navigator.language, {hour: '2-digit', minute:'2-digit'});
return time + ' ยท ' + date;
}
</script>
</body>
</html>
It works when I put the function before the loop but scripts are launched in footer to optimize the loading.
I'm looking for something better. Sorry for my poor english.
As Sanchit said, you could rewrite the
document.write(window.date('<?php echo $date;?>'));
part, as follows (if you use jQuery)
$(document).ready(function(){
// write here where needed: using jQuery the $('') approach is the easiest way
});
In this way, the script is executed once all the scripts are loaded in the page and all the functions are defined. Anyway, in this case if you move this function definition in the footer the bytes saved are partially used by the overhead required to fire the script when the page is ready.
Depending on the number of $post in the $topic, this approach could slow down the loading time. Maybe, it would be faster to put the definition in an external Javascript (so it can be cached by the browser) included in the header of the page.

Knob JQuery get value from textfile

I have been trying to make a script that would allow Knob to get a value from a text file every 3 seconds.
I had JS refresh a div that had php check the file and set the value to a variable. The issue was flickering and kept doubling the knob until it crashes chrome.
I tried this with PHP and didn't get far. Anyone have any ideas?
<script>
var dataFile = Server.MapPath("count.txt");
Array userData = File.ReadAllLines(dataFile);
function clock() {
$h = $(".hour");
d = new Date(),
h = "";
$h.val(h).trigger("change");
setTimeout("clock()", 1000);
}
clock();
</script>
<input class="knob hour" value="0" data-fgColor="#EB4B4E" data-thickness=".2" readonly data-min="0" data-max="50" data-width="300" data-height="300">
<script>
setTimeout(function(){
$('.dial')
.val(<?php echo file_get_contents("count.txt"); ?>)
.trigger('change');
},3000);
</script>

<script> tags not working following jQuery post

I am having a problem with jQuery where by it is not loading inside a requested div.
Setup:
On index.php I have 4 Morris charts on 4 tabs all working fine.
On each tab there is a list. Each item in the list is a link
Upon clicking the link the div within the tab reloads with new data
via post:
$(document).ready(function () {
$('.click5').click(function () {
companyId = $(this).attr('id');
$.post('./ajax/donut5.php', {
clickthrough5: $('#company5-'+companyId+' .clickthrough5').val(),
ref_date_from5: $('#company5-'+companyId+' .ref_date_from5').val(),
ref_date_to5: $('#company5-'+companyId+' .ref_date_to5').val()
},
function (data) {
$('.donut5').html(data);
});
});
});
The new div contains a back button to take you back to a replica of the 1st graph but on a different page (donut1.php), for my personal ease:
$(document).ready(function () {
$('.backref2').click(function () {
companyId = $(this).attr('id');
$.post('./ajax/donut1.php', {
clickthrough6: $('#company6-'+companyId+' .clickthrough6').val(),
ref_date_from6: $('#company6-'+companyId+' .ref_date_from6').val(),
ref_date_to6: $('#company6-'+companyId+' .ref_date_to6').val()
},
function (data) {
$('.donut5').html(data);
});
});
});
All this code works fine up until landing on donut1.php.
At this point I proceeded to pull out chunks of my hair for several hours looking through Inspect Element in Chrome to identify the issue.
1 bald person later I realised the jQuery was not loading although it is correctly requested in a script tag.
I confirmed this by placing the following on both donut1.php and donut5.php:
<div id="divTest1"></div>
<script type="text/javascript">
$("#divTest1").text("Hello, world!");
</script>
donut5.php displays the output fine while donut1.php does not.
I then tried to load an external source and a different version using the Google snippets found here but this still did not work.
Some points to note:
I currently have jquery loading in my header and footer as part of trying to work this out.
As the 2 pages donut1.php and donut5.php do not include header or footer I have manually included them both in there. Same exact way in both files. donut5.php works donut1.php does not.
Order is index.php > donut5.php > donut1.php and then you continue to cycle between donut5 and donut 1 - or you would if the post on click was working in donut1.php.
Any help would be greatly appreciated!
EDIT: donut1.php:
<?php
include("../../../includes/config.php");
$selected = $_POST['clickthrough6'];
$date_from = $_POST['ref_date_from6'];
$date_to = $_POST['ref_date_to6'];
?>
<script src="../../../js/jquery-1.11.0.js"></script>
<script>
$(document).ready(function () {
$('.click7').click(function () {
companyId = $(this).attr('id');
$.post('./ajax/donut5.php', {
clickthrough5: $('#company7-'+companyId+' .clickthrough7').val(),
ref_date_from5: $('#company7-'+companyId+' .ref_date_from7').val(),
ref_date_to5: $('#company7-'+companyId+' .ref_date_to7').val()
},
function (data) {
$('.donut5').html(data);
});
});
});
</script>
<div id="tabs2">
<div id="tabs-1" class="donut5">
<h4>Top 5 Referrers - Quotes <br /><small>Total number of Quotes between <?php echo date("d/m/Y", $date_from); ?> to <?php echo date("d/m/Y", $date_to); ?></small></h4>
<div class="statgrid">
<div id="divTest1"></div>
<script type="text/javascript">
$("#divTest1").text("Hello, world!");
</script>
<?php $quotes_q="SELECT
c.case_id,
co.name AS company_name,
co.company_id AS company_id,
COUNT(c.case_id) 'quote_count'
FROM
(`case` c,
`panel_company` pc,
`panel` p)
LEFT JOIN company co ON (co.company_id = pc.company_id)
WHERE pc.panel_id = " .$RegisteredUser['panel_id']. " AND
p.company_id = pc.company_id AND
c.panel_id = p.panel_id AND
c.insert_date > ".$date_from. " AND
c.insert_date < ".$date_to. "
GROUP BY p.panel_id
ORDER BY quote_count DESC, co.company_id
LIMIT 5";
$result=$mysqli->query($quotes_q); ?>
<div class="col-2-6">
<div id="morris-donut-chart6"></div>
</div>
</div>
<div class="statgrid">
<?php while ($row=$result->fetch_array()) { ?>
<div class="col-4-6">
<div id="company7-<?php echo $row['company_id'];?>">
<input type="hidden" class="ref_date_from7" value="<?php echo $date_from; ?>" />
<input type="hidden" class="ref_date_to7" value="<?php echo $date_to; ?>" />
<input type="hidden" class="clickthrough7" value="<?php echo $row['company_id'] ?>" />
<a><div id="<?php echo $row['company_id'];?>" class="click7 col-5-6"><?php echo $row['company_name']; ?></div></a>
<div class="col-1-6"><?php echo $row['quote_count']; ?></div>
</div>
</div>
<?php } ?>
</div>
</div>
</div>
<?php
$quotes_q = "SELECT
c.case_id,
co.name AS company_name,
COUNT(c.case_id) 'quote_count'
FROM
(`case` c,
`panel_company` pc,
`panel` p)
LEFT JOIN company co ON (co.company_id = pc.company_id)
WHERE pc.panel_id = ".$RegisteredUser['panel_id']." AND
p.company_id = pc.company_id AND
c.panel_id = p.panel_id AND
c.insert_date > ".$date_from." AND
c.insert_date < ".$date_to."
GROUP BY p.panel_id
ORDER BY quote_count DESC, co.company_id
LIMIT 5";
$result = $mysqli->query($quotes_q);
?>
<script>
var donut_data6 = [
<?php while ($row = $result->fetch_array()) { ?>
{
label: '<?php echo substr($row['company_name'],0,15); ?>',
value: '<?php echo $row['quote_count']; ?>'
},
<?php } ?>
];
var donut6 = {
element: 'morris-donut-chart6',
data: donut_data6,
resize: false
}
donut6 = Morris.Donut(donut6)
</script>
EDIT2:
Not too sure if this makes a different but in Network tab I have 2 listings for jquery the initial one loaded from the header which loads 304 Not Modified and the 2nd one which loads on calling donut5.php which loads as 200 OK. Seems that after this I cannot request jquery again perhaps?
EDIT3: in donut1.php I have removed everything except for the jquery script request and the Hello World inside the div I am trying to retrieve. Network tab still shows that jquery is not loading. The strange thing is I have this exact setup, minus the charts, working on the same page (different div classes of course), and this does load jquery fine.
EDIT4: Substituted jQuery for JS as a test and not even basic stand alone JS will work, added in:
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>
Nothing :( - Looping in JS world
EDIT5: Suppose <script> is a HTML tag so looping in them too.
EDIT6: When adding console.logo(data) to the function in list item 4 above I get back the following (obviously I have excluded a lot for testing:
<script src="../../../js/jquery-1.11.0.js"></script>
<script src="../../../js/jquery-ui.js"></script>
<!--
<script>
$(document).ready(function () {
$('.click7').click(function () {
companyId = $(this).attr('id');
$.post('./ajax/donut5.php', {
clickthrough5: $('#company7-'+companyId+' .clickthrough7').val(),
ref_date_from5: $('#company7-'+companyId+' .ref_date_from7').val(),
ref_date_to5: $('#company7-'+companyId+' .ref_date_to7').val()
},
function (data) {
$('.donut5').html(data);
});
});
});
</script>
-->
<div id="tabs2">
<div id="tabs-1" class="donut5">
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>
<div id="divTest1"></div>
<script type="text/javascript">
$("#divTest1").text("Hello, world!");
</script>
</div>
</div>
EDIT7:
Placing code here to confirm if I have correctly inplemented KevinB's suggestion.
var
contentSelector = '.donut5',
$content = $(contentSelector),
contentNode = $content.get(0);
var documentHtml = function (html) {
// Prepare
var result = String(html)
.replace(/<\!DOCTYPE[^>]*>/i, '')
.replace(/<(html|head|body|title|meta|script)([\s\>])/gi,'<div class="document-$1"$2')
.replace(/<\/(html|head|body|title|meta|script)\>/gi, '</div>');
// Return
return $.trim(result);
};
$(document).ready(function () {
$('.click5').click(function () {
companyId = $(this).attr('id');
$.post('./ajax/donut5.php', {
clickthrough5: $('#company5-' + companyId + ' .clickthrough5').val(),
ref_date_from5: $('#company5-' + companyId + ' .ref_date_from5').val(),
ref_date_to5: $('#company5-' + companyId + ' .ref_date_to5').val()
},
function (data) {
var
$data = $(documentHtml(data)),
$dataBody = $data.find('.donut5'),
$dataContent = $dataBody.find(contentSelector),
$menuChildren, contentHtml, $scripts;
// Fetch the scripts
$scripts = $dataContent.find('.document-script');
if ($scripts.length) {
$scripts.detach();
}
// Fetch the content
contentHtml = $dataContent.html() || $data.html();
$scripts.each(function () {
var $script = $(this),
scriptText = $script.text(),
scriptNode = document.createElement('script');
if ($script.attr('src')) {
if (!$script[0].async) {
scriptNode.async = false;
}
scriptNode.src = $script.attr('src');
}
scriptNode.appendChild(document.createTextNode(scriptText));
contentNode.appendChild(scriptNode);
});
console.log(data);
});
});
});
EDIT8:
After trying the code above in EDIT7 the .donut5 in no longer being pulled from donut5.php to index.php which was originally working. I can see that jquery doesn't duplicate anymore on Network tab when clicking the link for donut5.php (even though the call to it is still there). Currently either I assume I have not mapped a div correctly above as I did remove part of the class find code for :first as I felt it was not required or somehow I have managed to make things worse!
When you pass an htmlstring to .html, one of two things happen. It either gets inserted using .innerHTML, or it gets inserted using .empty().append(htmlString). Which one is chosen is based on the complexity of the htmlstring passed in.
If it's relatively simple, .innerHTML will be used and scripts will execute in the way you expected.
However, if it is more complex, the elements are first parsed and appended to a docFragment before being appended to the document. This middle step is what causes your problem because the javascript will be executed before the elements are part of document.
The only way to fix this issue is to forcibly delay the execution of the javascript by either coding the javascript in such a way that it's execution is in a callback that later gets called, or by removing the javascript from the htmlstring before appending it and then executing it after.
Below is an example of the former:
(function divTestLooper () {
if (!$("#divTest1").length) {
// the element didn't exist, lets wait a little longer...
return setTimeout(divTestLooper, 10);
}
$("#divTest1").text("Hello, world!");
})();
Here is an example of the latter:
https://github.com/browserstate/ajaxify/blob/master/ajaxify-html5.js#L60-L70
and
https://github.com/browserstate/ajaxify/blob/master/ajaxify-html5.js#L123-L135
and
https://github.com/browserstate/ajaxify/blob/master/ajaxify-html5.js#L158-L167
Of course, the best solution is likely to avoid this problem entirely by not including javascript in your partials.

How can I pass PHP variable to Datepicker in jQuery?

I'm trying to set the default date in datepicker with a variable I pass into the html from PHP. Here's a simplified version of both my control file and form:
control file:
<?php
function render($template, $values = []) {
// extract variables into local scope
extract($values);
// render template
require("$template");
}
$default_date = date("m/d/Y") ;
$default_date = strtotime($default_date);
$default_date = $default_date + 604800;
$default_date = date("Y,m-1,d",$default_date);
render("index_month2_form.php",['default_date'=> $default_date]);
?>
and here is the form:
<!doctype html>
<html lang="en">
<head>
<?php print "$default_date"; ?>
<meta charset="utf-8">
<title>jQuery UI Datepicker - Default functionality</title>
<link rel="stylesheet" href="jqueryui/css/swanky-purse/jquery-ui-1.10.4.custom.css">
<script src="/jqueryui/jquery-1.11.1.min.js"> </script>
<script src="jqueryui/js/jquery-ui-1.10.4.custom.min.js"></script>
<script type="text/javascript">
$(function() {
$("#mydate").datepicker ({
onSelect: function(dateText, inst) {
var dateAsString = dateText;
var date = $('#mydate').val();
}
})
//.datepicker("setDate",new Date());
.datepicker("setDate",new Date(2014,10-1,17));
});
</script>
</head>
<body>
<p>Date: <input type="text" id="mydate"></p>
</body>
</html>
If I use the commented line for setDate I get the current date. If I use the line I have I get the date 7 days forward. When I print $default_date at the top of the form I get 2014,10-1,17 but I can't firgure out of way to pass this into the script. Others have suggested using
The better solution is to assign returned PHP date variable to jQuery variable.
This can be done by following
var phpDate = "<?php echo $default_date; ?>";
Now, you need to assign that to datepicker
$("#mydate").datepicker("setDate",phpDate);
This works...
using echo is the way to go.
I would rather put it in the script rather than the input
I assume $default_date === "2014,10-1,17"
$(function() {
$("#mydate").datepicker ({
onSelect: function(dateText, inst) {
var dateAsString = dateText;
var date = $('#mydate').val();
}
})
//.datepicker("setDate",new Date());
.datepicker("setDate",new Date(
<?php
$date = explode(',', $default_date);
echo $date[0] . ',' . $date[1] . ',' . $date[2];
?>
));
};
edit:
As rss81 noticed it, destructuring the string to rebuild the exact same string is quite dumb. I dont know what I was thinking...
Nevertheless I'll let it like this for educational purpose.
exploding the string enables us to get an array of the string of each chunk separated by a coma. You could use it to reorder the string. For instance if you wanted to transform "2014,10-1,17" to "10-1,2014,17" that would be done by echo $date[1].','.$date[0].','.$date[2]
Echo enables us to output the html page as we like, making it dynamic. So here we are preprocessing the date argument of the .datepicker() by php.
Just give the input the relative value
<input type="text" id="mydate" value="<?php echo $yourdate; ?>">
This will init datepicker with you date value
Hope this helped and my apologies if this is not what you were looking for
You can use <?php echo not in the script, but in the body, in some display:none element with id. And then just to get the date with javascript from that element and set to datapicker
You could pass the $default_date value in a data attribute of an html element. For example:
<p id="myDate" data-date="<?php echo $default_date; ?>"></p>
After that you can extract it with with Jquery like this:
var date = $("#myDate").data("date");
You need to set date format in javascript part because it's create and problem with date.
You can set it given below
$("#datepicker").datepicker("option", "dateFormat", "yy-mm-dd ");

PHP Include inside DIV Styles Background

I've got a rotating image that changes daily and I'm trying to make this the background image of a DIV so I can have a menu over it. For some reason it just displays all the information inside the includes file instead of showing the daily image?
<div styles="background-image: url(<?php include('includes/promotions.php'); ?>)">MENU</div>
Inside the includes file:
<SCRIPT LANGUAGE="JavaScript">
today = new Date();
day = today.getDay();
arday = new Array("images/daily-offers/sunday.png", "images/daily-offers/monday.png", "images/daily-offers/tuesday.png", "images/daily-offers/wednesday.png", "images/daily-offers/thursday.png", "images/daily-offers/friday.png", "images/daily-offers/saturday.png");
document.write("<img src='"+arday[day]+"'>");
</script>`
I'm kind of new to this but I appreciate the help!
You are trying to put javascript into the style attribute of a div, this isn't possible. Either you need to have php code come up with the filename instead of using an include, or you need to create the div give it an id the use javascript (outside the div's style) to change the background-image.
<div id='changeme'>Menu</div>
<SCRIPT LANGUAGE="JavaScript">
today = new Date();
day = today.getDay();
arday = new Array("images/daily-offers/sunday.png", "images/daily-offers/monday.png", "images/daily-offers/tuesday.png", "images/daily-offers/wednesday.png", "images/daily-offers/thursday.png", "images/daily-offers/friday.png", "images/daily-offers/saturday.png");
//ASSUMING YOU HAVE JQUERY
$('#changeme').css('background-image',arday[day]);
</SCRIPT>
Or simply use php:
<?php
$arday = array("images/daily-offers/sunday.png", "images/daily-offers/monday.png", "images/daily-offers/tuesday.png", "images/daily-offers/wednesday.png", "images/daily-offers/thursday.png", "images/daily-offers/friday.png", "images/daily-offers/saturday.png");
$day = date('w');
?>
<div styles="background-image: url('<?php echo $arday[$day]; ?>')">MENU</div>
Or if the naming convention of the images is always the same you could simply do:
<div styles="background-image: url('images/daily-offers/<?php echo strtolower(date('l')); ?>.png')">MENU</div>
You can set the backgroundImage like this:
document.getElementById("mymenu").style.backgroundImage="url(...)";
Your code could go like this:
<div id="mymenu">MENU</div>
<SCRIPT LANGUAGE="JavaScript">
today = new Date();
day = today.getDay();
arday = new Array("images/daily-offers/sunday.png", ...);
document.getElementById("mymenu").style.backgroundImage="url('"+arday[day]+"')";
</script>`
You can't execute javascript inside an attribute like that.
You could try this - change the contents of your includes/promotions.php file to the following:
<?php
$day = strtolower(date('l'));
echo '<img src="images/daily-offers/' . $day . '.png">';
?>
Additionally, the attribute on your div should be style, not styles.
I would not use PHP to do that.
I would right the following javascript code at the page where you showing right now the div with the background.
<div id="bgdiv">MENU</div>
<SCRIPT LANGUAGE="JavaScript">
today = new Date();
day = today.getDay();
arday = new Array("images/daily-offers/sunday.png", "images/daily-offers/monday.png", "images/daily-offers/tuesday.png", "images/daily-offers/wednesday.png", "images/daily-offers/thursday.png", "images/daily-offers/friday.png", "images/daily-offers/saturday.png");
document.getElementById('bgdiv').style.backgroundImage = "url(' + arday[day] + ')";
</script>

Categories

Resources