2

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
4
  • update your full code.html+php+javascript. Commented Sep 15, 2016 at 10:02
  • 2
    You need to pass details as arguments as myFunction(details) Commented Sep 15, 2016 at 10:02
  • 1
    PHP servers are not interpreting PHP code in files with the extension .js by default. if you change your script file's name to script.php, the PHP code will be executed. Commented Sep 15, 2016 at 10:02
  • Where you include index.php file?? Commented Sep 15, 2016 at 10:06

6 Answers 6

1

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

Sign up to request clarification or add additional context in comments.

4 Comments

So I should have HTML, JS and PHP in the same file? Doesn't that get cluttered?
I tried your first example but it prints out "<?php echo $cookie; ?>"
@lolzDoe check my current code. i have taken your code sample and changed it. use it
Hm, I thinks it's beacuse I still used my HTML file. So I out the HTML inside the PHP and have an externa JS file? But I still can't get this to work. Could you create a gist and copy in all your code?
1

The external js file will not be parsed as php meaning that you cannot access that variable. You can save your js as php (NOT RECOMMENDED). alternatively a)

include that function at the bottom of the bottom of the php page:

<?php
  $cookie= "blueberry cake";
?>;
    //js further down the same page
  <script>
    var details = "<?php echo $cookie; ?>";
   function myFunction() { 
        document.getElementById("demo").innerHTML = details;
    }
 </script>

or b) declare a global variable in the php page so that the external js can access it:

//php page
    <?php
      $cookie= "blueberry cake";
    ?>;
<script> var details = "<?php echo $cookie; ?>";</script>


//js file
       function myFunction() { 
          //details will be accessible since it has been declared in the global space of the index.php page
            document.getElementById("demo").innerHTML = details;
       }

1 Comment

I tried your second example but it doesn't seem to do anything.
1

Encode the json object using json_encode, that is

<script> var details = "<?php echo json_encode($cookie); ?>";</script>

Comments

1

This should work perfectly:

With In-Document JS:

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

<html>

    <head>
        <script type="text/javascript">
            var details = "<?php echo $cookie; ?>";
            function myFunction() {
                document.getElementById("demo").innerHTML = details;
            }
        </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>

With External JS:

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

<html>

    <head>
        <script type="text/javascript">
            var details = "<?php echo $cookie; ?>";
        </script>
        <script type="text/javascript" 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>

script.js File:

    function myFunction() {
         // HAS ACCESS TO details WHICH IS ON THE GLOBAL SCOPE
         document.getElementById("demo").innerHTML = details;
    }

2 Comments

This doesn't work. Not sure why, I got all the files in the same folder. I tried both with inline js and external.
@loizDoe Your Problem is the file script.js. You cannot do PHP Operations there. See how it is done here. You create a Javascript Variable:details on the Global Scope and then you can access it from within any other Script like script.js... but the definition of the details should not be in the external file... (only accessed in those files not declared using php)
1

Remove the quotes around php, dude. You are assigning string instead of the php variable value.

var details = "'" + <?php echo $cookie; ?> + "'";

This will assign the actual $cookie value instead of the string '<? php echo $cookie; ?>'.

2 Comments

I have tried removing them but this causes my JS file not to execute at all.
Ah.... well, you cannot really use both js and php inside file with .js extension. You could put this particular part of code inside your index.php and inside <script></script> tag. Php would execute on the server and substitute the $cookie value and js would have the value ready when executed in the browser.
1

The php-script is run server-side, and the javascript is run client-side, and the two do not share some kind of scope.

In other words, the $cookie variable is assigned a value in php, but it isn't used. Then you use a variable in your javascript with the same name (but completely unrelated to the php variable), but since it is never assigned anything, it's undefined.

gavgrif offers some solutions to fix this.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.