Call javascript passing php variable

-4

I need to call a javascript by passing a php variable to it, when I put the whole script in php I can pass the variable like this location: '<?php echo $cidade;?>, BR' , but when I call it that <script src="clima.js"></script> I do not know how to tell it to the weather. js that the variable that it should use is the $ city that already exists in php

    
asked by anonymous 14.06.2016 / 07:24

2 answers

2

So I understand, you have defined the $cidade variable on the PHP page and want to reference it directly (using PHP code) in the clima.js file.

If this is the case it will not work because the <script src="clima.js"></script> block is interpreted by the browser (client) and not by the server (which is the case of PHP codes).

What you can do to get around this is in the PHP page insert such a code:

<script src="clima.js"></script>
<?php
// este elemento HTML faz a separação entre os códigos server e client side
?>
<input type="hidden" value="<?php echo $cidade;?>" id='idCidade'/>

<script>
// obtenção do parâmetro cidade
var idCidade = window.document.getElementById ('idCidade').value;

// função do arquivo clima.js
var result=getClima(idCidade);
alert(result);
</script>

It is good practice to separate the server side and client side codes (in your case, PHP and Javascript respectively). The more separated, the better for maintenance and understanding.

    
14.06.2016 / 11:08
1

Well I would recommend assigning the variable to an input and there in javascript you will capture the value.

    <input type="hidden" value="<?= $suavarial ?>" id='cidadeClima'/>

    <script>

     var getCidade = window.document.getElementById('cidadeClima').value;
     console.log(getCidade);

   </script>
    
14.06.2016 / 13:31