How to print php variables within a JS?

1

What I wanted to do, was to put inside a JS calendar the data I pull from B.D through PHP: Events in this format:

events: [{
    title: 'All Day Event',
    start: new Date(y, m, 1),
    backgroundColor: "#f56954", //red 
    borderColor: "#f56954" //red
  }, ],

I have done this function in PHP just to get all the events of the DB and put it inside a String:

  $eventosJS = "";
foreach($eventos as $key => $value) {
  $a = substr($value['data'], -19, 4);
  $m = substr($value['data'], -5, 2);
  $d = substr($value['data'], -2, 2);
  $hrI = substr($value['hora_inicio'], -8, 2);
  $minI = substr($value['hora_inicio'], -5,
    2);
  $hrF = substr($value['hora_fim'], -8, 2);
  $minF = substr($value['hora_fim'], -5, 2);
  $eventosJS = $eventosJS.
  ",".
  "{ title:'Teste ', start: new Date(".$a.
  ",".$m.
  ",".$d.
  ",".$hrI.
  ",".$minI.
  "), end: new Date(".$a.
  ",".$m.
  ",".$d.
  ",".$hrF.
  ",".$minF.
  "), backgroundColor:
  '#f39c12', borderColor: '#f39c12'
}
"; }

But I do not know how to put PHP inside JS.

    
asked by anonymous 04.08.2017 / 14:26

1 answer

0

Follow these steps:

  • First read your JS to a php variable, using the function: file_get_contents .

    $js = file_get_contents('caminho para seu js');
    
  • Within your JS where you want to print the values contained in the php array from your Database, create some identifiers:

    <script> var nome = %nome%; </script>
    
  • In your php code use the strtr function to replace the identifiers with the value coming from the DB.

    <?php
        // $values é minha variavel contendo valores do BD.
        $valores     = array('%nome%' => $values['nome']); 
        $code        = strtr($js,$valores);
        /* Indique o cabeçalho como javascript */
        header('Content-Type: application/javascript');
        // Encerre o script enviando o conteúdo do JS
        die($code);
    ?>
    
  • Finally in your html to bind the js just do this:

    <script type="text/javascript" src="seuarquivo.php"></script>
    
  • I hope this solves your problem.

        
    04.08.2017 / 14:54