I'm trying to create a video slideshow using a Javascript array. The array needs to be populated from a database loop. The database of videos is created through a CMS.
I am currently using "push" for my array, FeaturedVideos, but it's not working. How else do I put the returned string into the array?
<% control getFeaturedMedia %>
<script type="text/javascript">
FeaturedVideos.push('<div class="panel"><h3>$Title</h3><div class="videoBox"><% if Type = Vimeo %><iframe src="http://player.vimeo.com/video/$VideoID?title=0&byline=0&portrait=0" width="275" height="184" frameborder="0"></iframe><% else_if Type = YouTube %><iframe class="youtube-player" type="text/html" width="275" height="184" src="http://www.youtube.com/embed/$VideoID" frameborder="0"></iframe><% else %>$Image.SetSize(275,184)<% end_if %></div></div>');
</script>
<% end_control %>
1 Answer 1
You're inserting PHP values directly into Javascript. This can break the javascript, especially if there's anything in the PHP-generated text that will be interpreted by Javascript, particularly single quotes '. To make such a direct insertion safe, you should generate the entire string seperately:
$js_value = "<div class=........ blah blah blah ....";
and the insert it into the Javascript as JSON data:
FeaturedVideos.push(<?php echo json_encode($js_value); ?>);
The JSON encoding will take care of turning that string into a valid JS representation.
Right now, you've got the PHP/Javascript equivalent of SQL injection.
<% %>for php is not the best practice use<?php ?>...echo out the variable that you wish to interact w/ JS