Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial

Andrew Chappell
12,782 PointsHow to get data stored in a PHP variable into a javascript array?
I have a php variable $disablethese that results from this:
try {
$results = $db->prepare("SELECT fromDate, toDate FROM availability");
$results->execute();
} catch (Exception $e) {
echo "Data could not be retrieved.";
exit;
}
$disablethese = $results->fetch(PDO::FETCH_ASSOC);
And I want to retrieve the information stored in that variable and put into a javascript array to use with the Jquery UI datepicker like this:
var disablethese = ">>>>>PHP VARIABLE SHOULD GO HERE<<<<";
$('#fromDate').datepicker({
beforeShowDay: function (date) {
var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
return [disablethese.indexOf(string) == -1];
}
});
How would I do that?
2 Answers

Juan Jose Cortes Guzman
7,894 PointsHi, if it is a simple array you can use php's implode function to create a string and do a echo for pass those values into a variable in javascript, for simple values just do a echo.
//simple variable var val "<?php echo $var?>";
//a simple array
<?php
// numerically indexed array
$fruits = array('apple', 'orange', 'mango', 'banana', 'strawberry');
// use implode to build a string for JavaScript
$fruits_list = '["' . implode('", "', $fruits) . '"]';
?>
<script type="text/javascript">
// no quotes around PHP tags
var fruits_ar = <?php echo $fruits_list ?>;
// ["apple", "orange", "mango", "banana", "strawberry"]
</script>
You can check this page for more examples link

Andrew Chappell
12,782 PointsCould a moderator please delete this comment. I accidentally posted twice.
Andrew Chappell
12,782 PointsAndrew Chappell
12,782 PointsHi, thanks for that link. I think I need to use Json_encode because it is an associative array but my problem is my js file is in an external js file and my research so far has told me that php won't work in js files. Any ideas?