lolzDoe lolzDoe - 2 months ago 8
PHP Question

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?

Answer

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

Comments