0

i have my code like this :

<?php
include 'fonctions.php';

?>
<input type="button" onClick="chauffeur_info(330);" />
  <h1 id="header"></h1>
  <script>
    function chauffeur_info(matricule){
    console.log(matricule);
    var result = "<?php echo get_nom_prenom_chauffeur(matricule); ?>";
    document.getElementById("header").innerHTML = result;

    }
  </script>

when i call it like that it gives me an error, but when i do :

var result = "<?php echo get_nom_prenom_chauffeur(330); ?>";
document.getElementById("header").innerHTML = result;

it's working perfectly, any idea why it's not working.

PS: console.log is giving me the right value

Thanks in advance

zizouu
  • 1
  • 1
  • 1
    You cannot pass a javascript variable to PHP like that – evolutionxbox Nov 30 '21 at 14:15
  • @evolutionxbox how to do so then, i tried every possible way but didn't work for me – zizouu Nov 30 '21 at 14:16
  • 1
    Please read https://stackoverflow.com/questions/1917576/how-do-i-pass-javascript-variables-to-php. You need to use a `fetch` request using either GET or POST. – evolutionxbox Nov 30 '21 at 14:18
  • In the first case check the browser to see what the PHP actually returns. All PHP will be executed before any javascript starts on the same page. – mousetail Nov 30 '21 at 14:33
  • 1
    `any idea why it's not working`... because `matricule` is not a PHP variable (it's a JavaScript variable) so it's not valid PHP syntax and PHP doesn't have direct access to JS variables. And also because PHP runs server side, so its code runs _before_ your JS code, while the page is still being created. JS only runs after that page is received from the server and loaded into the browser. Therefore the _output_ of the PHP code can be used as static content in the finished JS and HTML, but not the other way round. To trigger the PHP again you need to send another request to the server. – ADyson Nov 30 '21 at 14:35

0 Answers0