0

I'm coding and I need to pass variables from javascript to PHP. I found the solution but it behaves a little different than expected

<script>
    var res = navigator.language;
</script>

<?php

$lang = "<script>document.writeln(res);</script>";

$string = file_get_contents("country.json");
if ($string === false) {
    // deal with error...
}

$json_a = json_decode($string, true);
if ($json_a === null) {
    // deal with error...
}
// echo $lang;
echo var_dump($lang); // On page it does display what I need and that is string(39) "sr-RS"
foreach ($json_a as $countryCodes) {
    // echo var_dump($countryCodes["twoLetter"]);
    if($lang == $countryCodes["twoLetter"]){
        echo "Success";
    }
}
?>

This is what I see on my page string(39) "sr-RS". In 39 characters it contains the <script>document.writeln(res);</script>. So I can not compare these two different values since they are different. Do you know how could I convert it or format it?

Matija
  • 46
  • 8
  • `On page it does display what I need`...yes, because at that point, your browser grabbed the Javascript and executed it. But that happens at the end of the process, _after_ the rest of your PHP code has already executed, and the entire output (of the PHP script) has been sent to the browser for rendering. `$lang`, in the context of the PHP script, always remains a string containing that ` – ADyson Jan 04 '22 at 15:12

0 Answers0