How to print php variables inside a JS?

Asked

Viewed 121 times

1

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

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

Being that I did this function in PHP just to take all the BD events and put 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 don’t know how to put PHP inside JS.

1 answer

0

Follow these steps:

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

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

    <script> var nome = %nome%; </script>
    
  3. In your php code use the function strtr to replace identifiers with value from 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);
    ?>
    
  4. Finally in your html to link the js just do this :

    <script type="text/javascript" src="seuarquivo.php"></script>
    

I hope this solves your problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.