You can use PHP to generate the string that is assigned to a JS variable like so:
var myvar = "<?php echo "Hello World"; ?>";
In your example you forgot the quotes around the PHP tags (before <?php
and after ?>
) so you were probably getting errors because the JS interpreter was looking for varables called Hello
and World
instead of considering "Hello World" as a string.
Now as we know, you can't have includes in JS as you would in other languages, what people normally do is just using multiple <script>
tags to include more than one JS into the page. However, if for some reason that I ignore, you absolutely need to include the JS into another JS, what you can do is using jquery's getScript()
, see here for more info https://api.jquery.com/jquery.getscript/:
$.getScript( "another-file.js" )
.done( function() {
alert(a + b);
})
.fail( function() {
console.log("Ooops there was a problem");
});
EDIT: as I said in my other comment you can also send an AJAX query and then eval()
(which is what getScript()
does behind the scenes), or you can use ES6 modules, but that's beyond the scope of this question.