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);

Read More

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!

Related posts

Leave a Reply

3 comments

  1. 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
    }
    
  2. if the php code is replaced and the script works fine means php is having some error while executing. can you please try to see the source code of the html page. this may be happening because of some php error happening and those error message string could be making some syntax error to javascript.

    try to put the php code outside the javascript tag and see the output generated from it.

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

    and then try to print the output in the javascript.

    executeList : [ "<?php print $output; ?>"]
        }
    

    by this way you can see if any php error is encountered.

  3. Replace "-" with '-' in Javascript code in line:

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