DrakeJest
DrakeJest

Reputation: 187

How to include in .php a .html with links to a .js that has php codes

I have a folder that basically contains:

Inside php i need to load .html to display the webpage of course. inside the html there is a script tag that refers to the .js file.

Now inside the JS file i have a php code that is needed to run there. But using my methods of loading the html the .js throws an error

PHP

<?php
  $value = 1;
  //$html = file_get_html('index.html')
  //include ("index.html")
  readfile('index.html');
?>

HTML

<html>
  <head>
    <script src="script.js"></script>
  </head>
  <body>
  </body>
</html>

Javascript

var myNum = <?php echo json_encode($value); ?>;

Unfortunately the way i have included the html thows an error in the .js file

Uncaught SyntaxError: Unexpected token '<'

What am i doing wrong? Are there any other way to include so that i will be able to write php code in my .js file. Unfortunatly im not allowed to change the file extention there can only be one php file. I separated the javascript and css file to make the code a bit cleaner

EDIT: A lot may seem to be misunderstanding, This is still hapening in the server, basically what i want is that the webpage recieved by the user already has the value for MyNum. I am initializing the variable before it even gets to the user

Upvotes: 0

Views: 769

Answers (2)

chriskirknielsen
chriskirknielsen

Reputation: 2939

In your PHP file, create a global variable containing your JSON in a tag:

<script>var myNum = <?php echo json_encode($value); ?>;</script>

and then reference that variable in your script file with myNum.

Upvotes: 3

Zoldszemesostoros
Zoldszemesostoros

Reputation: 397

PHP code runs on the server, the client (the browser in this case) will get only the output of the PHP. In fact, browsers can't execute PHP code.
JavaScript runs in the client. The browser gets the JavaScript code, and executes it. The only thing you can do if you really want to produce JS code from PHP is to give a .php ending for the js file (test.js -> test.js.php).
With this, the file will interpreted as PHP. The browser gets the result (javascript, that contains the encoded JSON), and everything works well. If you want to pass $value from the first PHP to test.js.php, read about GET variables.

Upvotes: 0

Related Questions