Search code examples
javascriptphphtmltransfer

Cannot get value from PHP to Javascript


So in my PHP file I create a JSON Object which I need to get to my Javascript file for processing. I can't seem to transfer anything however, not even with a simple string like this:-

index.php

<?php
  $cookie= "blueberry cake";
?>;

script.js

   var details = "<?php echo $cookie; ?>";
   function myFunction() { 
        document.getElementById("demo").innerHTML = details;
   }

index.html

<html>

<head>
    <script src="script.js"></script>
    <title>antgus</title>
</head>
<body>

    <h1>Welcome to my page! </h1>

    <button type="button" onclick="myFunction()">Try it</button>

    <p id="demo">A Paragraph.</p>


</body>

I got a button in my HTML, so when I press it the function myFunction get's called. It's supposed to change a p element with id "demo" to the string "blueberry cake"

Any idea what I'm doing wrong here?

EDIT

I now have it working except one thing, I can't pass a JSON object to a function i Javascript. The console throws an error saying that the arguments is wrong, it thinks I am passing multiple strings. index.php

    <?php
    $test = "blue";
    $logLines = file('../../../home/shares/flower_hum/humid.log');
    $entries = array_map("clean",$logLines);
    $finalOutput = [
        'humid'   => $entries
    ];
    function clean($string){
        return json_decode(rtrim(trim($string),','),true);
    }

    $json = json_encode($finalOutput, JSON_UNESCAPED_SLASHES);
    echo $json; //displays valid JSON, I have checked it.
?>

<html>
    <head>
        <script src="script.js"></script>
        <title>antgus</title>
    </head>
    <body>
        <p>Welcome to my page! Down below you can see the data:</p>
        <button type="button" onclick='myFunction("<?php echo $json ?>")'>Try it</button>
        <p id="demo">A Paragraph.</p>
    </body>
</html>

script.js

function myFunction(jsonObject) {
    document.getElementById("demo").innerHTML = "INCOMING DATA:";
    alert(jsonObject);
}
    enter code here

Solution

  • Things to consider:-

    1.External js will not work as you tried.

    2.When you call a javascript function directly through onclick code then you have to pass data also for working further.

    A working code sample:-

    index.php:-

    <?php
      $cookie= "blueberry cake";
    ?>
    <html>
    
    <head>
        <script src="script.js"></script>
        <title>antgus</title>
    </head>
    <body>
    <h1>Welcome to my page! </h1>
    
    <button type="button" onclick='myFunction("<?php echo $cookie; ?>")'>Try it</button>
    
    <p id="demo">A Paragraph.</p>
    

    script.js:-

    function myFunction(details) { 
        document.getElementById("demo").innerHTML = details;
    }
    

    Output at my local end:-

    before click:- http://prntscr.com/ci94s9

    After click:-http://prntscr.com/ci94w9