Reputation: 4187
I have a file php javascript
in news.js
news_id = 1;
document.write('<div id="news-id"></div>');
function output(strHtml) {
document.getElementById('news-id').innerHTML = strHtml;
}
in news.php is using
<?php
$news_id =
?>
news_id
<?php
$str = '<p>This is id: </p>'.$news_id;
?>
output(<?php echo json_encode($str); ?>);
And index.html i call
<script src="news.js" type="text/javascript"></script>
<script src="news.php" type="text/javascript"></script>
When i run index.html
is error, how to get news_id
from js
to using in php
Upvotes: 1
Views: 3597
Reputation: 8640
Well, as wrong as the original question is, there is a way to get the a JS variable into a PHP file.
In the HTML:
<script src="news.js"></script>
<script>
document.write('<scr'+'ipt type="text/javascript" src="news.php?myvar='+myvar+'" ></scr'+'ipt>');
</script>
In news.js:
var myvar = "HELLO";
In news.php:
alert("<?php echo $_GET["myvar"]?>");
Again, I highly discourage this approach... but it works.
Upvotes: 1
Reputation: 3939
To use PHP as javascript source <script src="news.php"
you need explicit declare content-type in .php
<?php header("Content-type: text/javascript"); //at very first line no white-space before ?>
//this is javascript content..
first, PHP execute on web server and send response to client(browser).
then javascript execute later in web browser.
To use js value inside php function you need AJAX GET/POST.
Upvotes: 0
Reputation: 191
You can't call news.php like this. It should be included in the html file like this:
include("news.php");
and you should change the extension of your html file to .php
Upvotes: 1