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
Dennis Eitner
Full Stack JavaScript Techdegree Graduate 25,644 PointsHow do I get values form a php foreach to a javascript variable
How do I get variables from a foreach loop to be assigned to a javascript variable so that the foreach loop also works with javascript.
<?php
$args = array ('post_type' => 'events', 'posts_per_page' => 5 );
$myposts = get_posts( $args );
$i=0;
foreach ( $myposts as $post ) { ?>
<li>
<?php the_title(); ?>
</li>
<?php }; ?>
<script type="text/javascript">
// <![CDATA[
$(document).ready(function(){
$('#stuff').airport(['<?php echo POST_TITLE;?>','<?php echo POST_TITLE;?>','<?php echo POST_TITLE;?>']);
});
// ]]>
</script>
1 Answer
Iban Dominguez
17,973 PointsHi there, assuming you are building on top of wordpress I think this might be what you are looking for
<?php
// get posts
$args = array ('post_type' => 'events', 'posts_per_page' => 5 );
$myposts = get_posts( $args );
// store desired values on
// a reusable array
// if using get_posts you might consider
// reseting the post query
$titles = array();
foreach ( $myposts as $post ) {
$titles[] = $post->post_title;
}
?>
<!--
this will output a unordered list
-->
<ul>
<li><?php echo implode("</li><li>", $titles); ?></li>
</ul>
<!--
this will output a proper quote
comma separeted list of array items
-->
<script>
$(document).ready(function(){
$('#stuff').airport(['<?php echo implode("','", $titles); ?>']);
});
</script>
You might wanna check a count() on the titles array if you do not want to do some stuff if there are not items.
Good luck ;)
Dennis Eitner
Full Stack JavaScript Techdegree Graduate 25,644 PointsDennis Eitner
Full Stack JavaScript Techdegree Graduate 25,644 PointsThank you very much, Iban!