Running Javascript+PHP Form Another File -


how execute javascript+php in file in current.js file?

the scenario follows:

another-file.js

function foo() {     var = <?php echo "hello world !"; ?> } 

current.js

function show() {     var b = "hi,";     // execute javascript (with php code embeded)     require(another-file.js)  // <-- not work      alert(a + b); // want result: "hi, hello world !" } 

you can use php generate string assigned js variable so:

var myvar = "<?php echo "hello world"; ?>"; 

in example forgot quotes around php tags (before <?php , after ?>) getting errors because js interpreter looking varables called hello , world instead of considering "hello world" string.

now know, can't have includes in js in other languages, what people using multiple <script> tags include more 1 js page. however, if reason ignore, absolutely need include js js, can using jquery's getscript(), see here more info https://api.jquery.com/jquery.getscript/:

$.getscript( "another-file.js" )     .done( function() {         alert(a + b);     })     .fail( function() {          console.log("ooops there problem");     }); 

edit: said in other comment can send ajax query , eval() (which getscript() behind scenes), or can use es6 modules, that's beyond scope of question.


Popular posts from this blog

php - How should I create my API for mobile applications (Needs Authentication) -

5 Reasons to Blog Anonymously (and 5 Reasons Not To)

Google AdWords and AdSense - A Dynamic Small Business Marketing Duo