1

I notice that I can substitue PHP into JavaScript that's place inline in the HTML, as below:

<script>  
    jQuery('select#age_group').val(<?php echo $age_group?>); 
</script>

But the PHP substitution doesn't work inside a .js file that the PHP file loads. Why is that and how can I do the substituion in the loaded .js file?

2
  • Because php knows nothing about any css/js files you include. Commented Mar 27, 2016 at 14:21
  • You have to add .js to the file extensions PHP processes. Presumably this is part of your httpd.conf Commented Mar 27, 2016 at 14:22

5 Answers 5

1

Here are two ways you can do this without changing the file extensions that the PHP engine can process.

First, you can set a global variable inline and then access that variable in the JS you include.

<script>global_age_group = <?php echo $age_group?>;</script>

<script src="js_that_accesses_age_group.js" /></script>

(standard warnings about global variables apply)

Second, you can give your JS file a .php extension, so...

<script src="js_that_accesses_age_group.php" type ='application/javascript'/></script>

And then use

<?php echo $age_group?> 

in that file as you do in your inline example.

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

Comments

1

Try this instead... Let me know if it works

    </form>
</div>
<?php echo"<script>  
        jQuery('select#age_group').val($age_group); 
</script>";
?>
</body>
</html>

2 Comments

Yes, that works. Is there some advantage to doing it that way?
No particular advantage @Steve This just make your code simple and easy to understand when you visit it next time.
0

you pass the value on a element attribute or on js var as you did

<script>
var age = 20;
</script>
<script src="main.js"></script>

and your can use the age inside main.js

Comments

0

By default, PHP will only process files ending in certain extensions (most commonly .php). If you want to use PHP in a JavaScript file then the easiest way to do it is to give it a .php extension.

Most browsers will also refuse to process your JavaScript unless it has the right content type, so at the top of your file add

<?php
header("Content-Type: application/javascript");

Comments

-1

The Simple answer that you can't !

You can't write a PHP script any where except .php files, That you can't write php scripts in .html, .css or .js files because the compiler will not pass .js file or .html file to read it!

1 Comment

"you can't" is wrong. As others have said one can change the extensions that the PHP engine processes, or one could use a PHP extension for the JS file.

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.