How can I pass PHP variable to Datepicker in jQuery? - javascript

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 ");

Related

fullcalendar php global variable to external JS file

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

How To use PHP variable in jQuery (in Wordpress plugin)

This is wordpress plugin code The following code works, but no text comes into the modal window. Error is this enter image description here
<?php
$phpvariabletext = get_post_meta( $post_id, '_billing_satis_sozlesme', true );
// $phpvariabletext large text along with html codes
?>
<a class="classa" id="view" onclick="openmodal()"> Show Contract </a>
<script type="text/javascript">
var content = '<?php echo $phpvariabletext; ?>';
var newmodal = new tingle.modal();
function openmodal() {
newmodal.open();
newmodal.setContent(content);
}
</script>
You can use PHP variable in JQuery/Javascript easily check below steps
1) Stored PHP variable value in HTML input tag as type hidden
<input type="hidden" value="<?php echo $phpvariabletext;?>" id="phpvariable">
2) After assign variable value in HTML input tag. You can get value in JQuery/Javascript.
<script type="text/javascript">
var content = $('#phpvariable').val();
var newmodal = new tingle.modal();
function openmodal() {
newmodal.open();
newmodal.setContent(content);
}
</script>
Creating extra DOM elements solely to transport a value is needless extra markup.
I always pass php data to javascript as json_encode() output (without manually quoting) because it will automatically double-quote your string and escape any of the double-quotes in the actual data.
<a class="classa" id="view" onclick="openmodal()"> Show Contract </a>
<script type="text/javascript">
let newmodal = new tingle.modal();
function openmodal() {
newmodal.open();
newmodal.setContent(<?= json_encode(get_post_meta($post_id, '_billing_satis_sozlesme', true)); ?>);
}
</script>
The above technique outputs the php value using php "short tags".
P.s. you could also consider removing the inline js function call and use an event listener in your js to keep all of the behaviors/events in one place.

passing variables to function with jquery

I'm new to javascript although I do use PHP.
I'm having issues passing variables using javascript/jquery on an onclick event on a href.
I'm pulling json data from a remote URL and there are 3 parameters that need to go with each request.
Date, price and currency.
I have a function to build the URL that looks like this:
function getIndexData(date, price, currency){
ajaxURL = "/data/"+date+"/"+price+"/"+currency+"";
}
This works well and builds the URL I need.
However, I have a jquery datepicker on the page to change the date to whatever I want which looks like:
$(function () {
$("#datepicker").datepicker(
{
dateFormat: 'yymmdd',
onSelect: function (date) {
getIndexData(date, price, currency )
}
}
);
});
Even if price and currency have previously been set they are now 'undefined'.
I have the same issue with the onclick events - if I try to send the price or the currency using (for example):
NET</span>
price and currency are undefined.
Is there a way I can send only one of the variables to my function whilst retaining the already existent values?
Apologies for what must be a really basic question. I'm just new to this and I've obviously misunderstood something along the way.
Ok so here is the updated answer. As you can see, if variables are declared in the global scope of the code, the date picker function will have access to it. I think it previously did not work because the html was wrong. I deleted all of the html and included only the date picker and if you test it in the browser, you will see that in the console the price, currency variables are available inside date picker onSelect function and you can also execute the function getIndexData inside it. I've assigned the function to a variable that way you can use the variable getIndexData if you want to use the function.
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<div class="col-sm-5 index-grid">
<span class="grid-label">Price</span>
<span class="btn btn-grid">CLOSE</span>
<span class="btn btn-grid">RETURN</span>
<span class="btn btn-grid">NET</span>
</div>
<p>Date: <input type="text" id="datepicker"></p>
</body>
</html>
<script>
var ajaxURL;
var indexDate = "2017-08-20"
var indexPrice = "closeprice";
var indexCurrency = "EUR";
var getIndexData = function (indexDate, indexCurrency, indexPrice) {
ajaxURL = "/data/" + indexDate + "/" + indexPrice + "/" + indexCurrency + "";
alert(ajaxURL);
}
$(document).ready(function() {
$(function() {
$("#datepicker").datepicker({
dateFormat: 'yymmdd',
onSelect: function(date) {
console.log(date);
console.log(indexPrice);
console.log(indexCurrency);
console.log(getIndexData);
}
});
});
});
</script>
If you declared price and currency outside of :
$(function () {
$("#datepicker").datepicker(
{
dateFormat: 'yymmdd',
onSelect: function (date) {
getIndexData(date, price, currency )
}
}
);
});
Then what you need to do is use the "this" keyword to access the values of price and currency. Just like the example below.
You may also want to check this link for more insight : https://javascriptplayground.com/blog/2012/04/javascript-variable-scope-this/
$(function () {
$("#datepicker").datepicker(
{
dateFormat: 'yymmdd',
onSelect: function (date) {
getIndexData(date, this.price, this.currency )
}
}
);
});

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>

NaN or blank value for calculated JS var

I have the following javascript:
<script type="text/javascript">
function changeBet(parseFloat(bet)) {
var moneyline = parseFloat(<?php echo json_encode($win) ?>);
var gain = parseFloat(bet * moneyline);
document.getElementById("PotentialGain").value = gain;
}
</script>
The php variable $win is successfully var_dump'ed as a float. When the variable gain = bet, PotentialGain displays the user input from BetAmount as expected. Here is my echo'ed php code:
echo '<tr>';
echo '<td>type="text" name="BetAmount[]" id="BetAmount" onkeyup="changeBet(this.value);" ></td></tr><tr><td>Potential Gain:<input type="text" name="PotentialGain[]" id="PotentialGain" ></td></tr><tr><td><input type="Submit" name="send" value="Submit"></td>';
echo '</tr>';
However, I want gain(which is inputted as the PotentialGain value) to be the user input bet * the var moneyline.
The result is NaN. Is there a var that I am not parsing correctly to display the correct numerical value of gain?
Thanks for any help.
You can't put a function call where a parameter name is expected.
function changeBet(bet) {
bet = parseFloat(bet);
// rest of code
}
The problem is the incorrect syntax in this line:
function changeBet(parseFloat(bet)) {
you need to pass a parameter to the function, like this:
function changeBet(bet) {
Then, when you call the function, you can evaluate whatever argument you want to send through parseFloat:
changeBet(parseFloat(strBet));
Here is the final javascript that I used:
<html>
<script type="text/javascript">
function changeBet(bet) {
var moneyline = <?php echo $win ?>;
var gain = (bet * moneyline).toFixed(2);
document.getElementById("PotentialGain").value = gain;
}
</script>
</html>
My final notes are: 1. To remember to place the javascript function after the code with your php caclculations. 2. Thanks to everyone who clarified parseFloat is not necessary if you know the var is a int (or double in my case). 3. Thanks to everyone who clarified parseFloat did not belong in the function parameter.
Hopefully this helps others out!

Categories

Resources