you can use $.parseJSON
function.
<script type="text/javascript">
var unavailabledates = $.parseJSON('<?php echo json_encode($disablethese); ?>');
</script>
<script src="js/datepicker-admin.js"></script>
Question
Right now I am using a manually inputted array of dates called disable to disable dates in the jquery UI datepicker with the beforeShowDay method. This is working fine, however, I have a php variable $disablethese which is storing a dynamic array of dates to disable. For some reason, I can't seem to convert my php array into a javascript array (which I'm calling unavailabledates). It doesn't throw any errors but it just doesn't work block out the dates the same way as the static array.
<script type="text/javascript">
var unavailabledates = <?php echo json_encode($disablethese); ?>;
</script>
<script src="js/datepicker-admin.js"></script>
Here is datepicker-admin.js
$(document).ready(function() {
var disable = ["2014-01-03","2014-01-13","2014-01-23"];
$('#fromDate').datepicker({
beforeShowDay: function(date) {
if($.inArray($.datepicker.formatDate('yy-mm-dd', date ), disable) > -1) {
return [false, "highlighted", "Booked out"];
} else {
return [true, "", "available"];
}
}
});
});
Solution
you can use $.parseJSON
function.
<script type="text/javascript">
var unavailabledates = $.parseJSON('<?php echo json_encode($disablethese); ?>');
</script>
<script src="js/datepicker-admin.js"></script>
OTHER TIPS
You can use .push
to insert all values to an array.
<script type="text/javascript">
var unavailabledates = new Array();
<?php
$disbaleddates = json_encode($disablethese);
for($i=0;$i<count($disbaleddates);$i++) { ?>;
unavailabledates.push('<?=$disbaleddates[$i]?>');
<?php } ?>
</script>
<script src="js/datepicker-admin.js"></script>
This may solve your problem, But it's might have a long way!! :)
You can use directly JSON.parse()
var unavailabledates = JSON.parse(<?php echo json_encode($disablethese); ?>);
1) Create a hidden field in php page:
<input id="disable-dates" type="hidden" value="<?php echo json_encode($disablethese); ?>">
2) Use jquery :
<script type="text/javascript">
var unavailabledates = $.parseJSON($('#disable-dates').val());
</script>
Both simulatneously
Did you assign your unavailabledates in
var disable = ["2014-01-03","2014-01-13","2014-01-23"];
like
var disable = unavailabledates;
I'm using laravel and this works beautifully:
var something = JSON.parse('{!! json_encode(['foo' => 'bar']) !!}');
I was very confused for a little bit cause I couldn't figure out why this DOES NOT work:
var something = JSON.parse('{{ json_encode(['foo' => 'bar']) }}');
the second way escapes HTML entities in the document. but yea, that's only with laravel.
var obj = <?php echo json_encode($_GET) ?>;