pradip pradip - 12 days ago 6
PHP Question

How to insert php code inside javascript

Kindly pls have a look at the code below ! Its working perfectly except the php code is not giving any output. When i insert the output of the php , the script work perfectly.

<script type="text/javascript">
function LoadVideoBar() {
var videoBar;
var barContainer = document.getElementById("videoBar");

var options = {
largeResultSet : false,
horizontal : true,
autoExecuteList : {
cycleTime : GSvideoBar.CYCLE_TIME_SHORT,
cycleMode : GSvideoBar.CYCLE_MODE_LINEAR,
executeList : [ "<?php $cat = get_the_category(); $cat = $cat[0]; echo $cat->cat_name; echo "-"; echo wp_title(); ?> "]
}
}

new GSvideoBar(
document.getElementById("videoBar"),
document.getElementById("videoPlayer"),
options
);
}
GSearch.setOnLoadCallback(LoadVideoBar);




When i replace the php code

<?php $cat = get_the_category(); $cat = $cat[0]; echo $cat->cat_name; echo "-"; echo wp_title(); ?>


with some text like : categoryname-title name

The script works perfectly.

Can somebody help me out with this small issue ...

Many Thanks in Advance!

Answer

If you ever need to pass data between the two. Put the PHP value into a hidden field. then read it like you did with bar container

Save the value from PHP:

<?php $cat = get_the_category(); $cat = $cat[0]; ?>
<input id="executeListValue" type="hidden" 
       value="<?php echo $cat->cat_name."-".wp_title();?>" >

read it in js:

var executeListValue = document.getElementById("executeListValue").value;
//...
autoExecuteList : {
  cycleTime : GSvideoBar.CYCLE_TIME_SHORT,
  cycleMode : GSvideoBar.CYCLE_MODE_LINEAR,
  executeList : executeListValue
}