-1

A JS function needs a variable, generated by PHP. The .js files can't interpret <?php ?> strings, so I must pass it from the .html code.

Yes, but running JS code from HTML considered bad practice (just like style elements). Then what to do?

Interrobang
  • 16,984
  • 3
  • 55
  • 63
John Smitth
  • 121
  • 2
  • 12
  • 2
    Do what you suggest: run JS code from HTML – bozdoz Feb 18 '13 at 22:11
  • I think you can also configure apache to read php code in js files, as an alternative. – bozdoz Feb 18 '13 at 22:11
  • Make a global namespace and echo a `json_encode`d object with the data you need on it. JSON encoded strings are valid JS object literals so you you won't even have to parse it. – Fabrício Matté Feb 18 '13 at 22:12
  • possible duplicate of [How to pass JavaScript variables to PHP?](http://stackoverflow.com/questions/1917576/how-to-pass-javascript-variables-to-php) oops or maybe [How to access PHP variables in JavaScript or jQuery rather than ](http://stackoverflow.com/questions/1808108/how-to-access-php-variables-in-javascript-or-jquery-rather-than-php-echo-vari) – Wesley Murch Feb 18 '13 at 22:14
  • do a search next time... same question comes up at least daily here – charlietfl Feb 18 '13 at 22:22
  • but all of them was solved by coding JS into HTML, thats why I wanted something else – John Smitth Feb 18 '13 at 22:30

3 Answers3

1

You could use echo to do something like this:

<? echo('<script type="text/javascript">var hello="world"</script>');
Elliot Bonneville
  • 51,872
  • 23
  • 96
  • 123
1

There are a couple of options. Firstly you can build off your first example.

<?php

$myVariable = array('key' => 'value', 'anotherKey' => 10);

?>

// PHP variable output in javascript's object syntax
var phpData = <?php echo json_encode($myVariable); ?>;

// value
console.log(phpData.key);
// 10
console.log(phpData.anotherKey);

Another option would be to use Ajax requests to the PHP script to retrieve data. Based on your question, this option most likely won't be useful because you have the data when the page loads.

Austin Brunkhorst
  • 20,704
  • 6
  • 47
  • 61
1

The .js files can't interpret <?php ?> strings

So give the file a .php extension. (Make sure you override PHP's default Content-Type output with a header() call.

but running JS code from HTML considered bad practice (just like style elements).

That's because inlining JS is bad for caching. If the file is being dynamically generated, then you may not be able to sanely cache it anyway.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335