How to execute javascript+php in another file in current.js file?
The scenario as follows:
another-file.js
function foo()
{
var a = <?php echo "Hello world !"; ?>
}
current.js
function show()
{
var b = "Hi,";
// execute javascript (with php code embeded)
require(another-file.js) // <-- this is not work
alert(a + b); // I want result: "Hi, Hello World !"
}
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.
There's a couple things wrong here.
You cannot execute PHP code in a JavaScript file. PHP is a server-side language, JavaScript is (traditionally) a client-side language. You can't execute PHP code with a JavaScript interpreter, or vice versa.
You cannot include a JavaScript file from another JavaScript file. Rather, you must include both scripts on a webpage, like this:
<body>
<script src="file1.js"></script>
<script src="file2.js"></script>
<script>
functionFromFile1();
functionFromFile2();
</script>
</body>
I feel like there is a disconnect here that needs to be resolved.
Related
I have a very simple question about php. In PHP, can we have script function, javascript or any other script in php section without script tag. Something like this:
<?php
function javascript_or_any_other_script_function() {
}
?>
I am aware that the question is pretty naive (almost silly) but I wanted to see whether php supports this syntax.
Thanks in advance,
PHP is in the server, JavaScript is in the browser...
To get JavaScript in client(browser), you need to output it in php...
function javascript_function() {
return 'function foo() {alert("working");}';
}
print('<script>');
print( javascript_function() );
print('</script>')
How to call a JavaScript function from PHP?
<?php
jsfunction();
// or
echo(jsfunction());
// or
// Anything else?
The following code is from xyz.html (on a button click) it calls a wait() in an external xyz.js. This wait() calls wait.php.
function wait()
{
xmlhttp=GetXmlHttpObject();
var url="wait.php"; \
xmlhttp.onreadystatechange=statechanged;
xmlhttp.open("GET", url, true);
xmlhttp.send(null);
}
function statechanged()
{
if(xmlhttp.readyState==4) {
document.getElementById("txt").innerHTML=xmlhttp.responseText;
}
}
and wait.php
<?php echo "<script> loadxml(); </script>";
where loadxml() calls code from another PHP file the same way.
The loadxml() is working fine otherwise, but it is not being called the way I want it.
As far as PHP is concerned (or really, a web server in general), an HTML page is nothing more complicated than a big string.
All the fancy work you can do with language like PHP - reading from databases and web services and all that - the ultimate end goal is the exact same basic principle: generate a string of HTML*.
Your big HTML string doesn't become anything more special than that until it's loaded by a web browser. Once a browser loads the page, then all the other magic happens - layout, box model stuff, DOM generation, and many other things, including JavaScript execution.
So, you don't "call JavaScript from PHP", you "include a JavaScript function call in your output".
There are many ways to do this, but here are a couple.
Using just PHP:
echo '<script type="text/javascript">',
'jsfunction();',
'</script>'
;
Escaping from php mode to direct output mode:
<?php
// some php stuff
?>
<script type="text/javascript">
jsFunction();
</script>
You don't need to return a function name or anything like that. First of all, stop writing AJAX requests by hand. You're only making it hard on yourself. Get jQuery or one of the other excellent frameworks out there.
Secondly, understand that you already are going to be executing javascript code once the response is received from the AJAX call.
Here's an example of what I think you're doing with jQuery's AJAX
$.get(
'wait.php',
{},
function(returnedData) {
document.getElementById("txt").innerHTML = returnedData;
// Ok, here's where you can call another function
someOtherFunctionYouWantToCall();
// But unless you really need to, you don't have to
// We're already in the middle of a function execution
// right here, so you might as well put your code here
},
'text'
);
function someOtherFunctionYouWantToCall() {
// stuff
}
Now, if you're dead-set on sending a function name from PHP back to the AJAX call, you can do that too.
$.get(
'wait.php',
{},
function(returnedData) {
// Assumes returnedData has a javascript function name
window[returnedData]();
},
'text'
);
* Or JSON or XML etc.
I always just use echo "<script> function(); </script>"; or something similar. You're not technically calling the function in PHP, but this is as close as you're going to get.
Per now (February 2012) there's a new feature for this. Check here
Code sample (taken from the web):
<?php
$v8 = new V8Js();
/* basic.js */
$JS = <<< EOT
len = print('Hello' + ' ' + 'World!' + "\\n");
len;
EOT;
try {
var_dump($v8->executeString($JS, 'basic.js'));
} catch (V8JsException $e) {
var_dump($e);
}
?>
You can't. You can call a JS function from HTML outputted by PHP, but that's a whole 'nother thing.
If you want to echo it out for later execution it's ok
If you want to execute the JS and use the results in PHP use V8JS
V8Js::registerExtension('say_hi', 'print("hey from extension! "); var said_hi=true;', array(), true);
$v8 = new V8Js();
$v8->executeString('print("hello from regular code!")', 'test.php');
$v8->executeString('if (said_hi) { print(" extension already said hi"); }');
You can refer here for further reference:
What are Extensions in php v8js?
If you want to execute HTML&JS and use the output in PHP http://htmlunit.sourceforge.net/ is your solution
Thats not possible. PHP is a Server side language and JavaScript client side and they don't really know a lot about each other. You would need a Server sided JavaScript Interpreter (like Aptanas Jaxer). Maybe what you actually want to do is to use an Ajax like Architecture (JavaScript function calls PHP script asynchronously and does something with the result).
<td onClick= loadxml()><i>Click for Details</i></td>
function loadxml()
{
result = loadScriptWithAjax("/script.php?event=button_clicked");
alert(result);
}
// script.php
<?php
if($_GET['event'] == 'button_clicked')
echo "\"You clicked a button\"";
?>
I don't accept the naysayers' answers.
If you find some special package that makes it work, then you can do it yourself! So, I don't buy those answers.
onClick is a kludge that involves the end-user, hence not acceptable.
#umesh came close, but it was not a standalone program. Here is such (adapted from his Answer):
<script type="text/javascript">
function JSFunction() {
alert('In test Function'); // This demonstrates that the function was called
}
</script>
<?php
// Call a JS function "from" php
if (true) { // This if() is to point out that you might
// want to call JSFunction conditionally
// An echo like this is how you implant the 'call' in a way
// that it will be invoked in the client.
echo '<script type="text/javascript">
JSFunction();
</script>';
}
Ordering It is important that the function be declared "before" it is used. (I do not know whether "before" means 'lexically before' or 'temporally before'; in the example code above, it is both.)
try like this
<?php
if(your condition){
echo "<script> window.onload = function() {
yourJavascriptFunction(param1, param2);
}; </script>";
?>
you can try this one also:-
public function PHPFunction()
{
echo '<script type="text/javascript">
test();
</script>';
}
<script type="text/javascript">
public function test()
{
alert('In test Function');
}
</script>
PHP runs in the server. JavaScript runs in the client. So php can't call a JavaScript function.
You may not be able to directly do this, but the Xajax library is pretty close to what you want. I will demonstrate with an example. Here's a button on a webpage:
<button onclick="xajax_addCity();">Add New City</button>
Our intuitive guess would be that xajax_addCity() is a Javascript function, right? Well, right and wrong. The cool thing Xajax allows is that we don't have any JS function called xajax_addCity(), but what we do have is a PHP function called addCity() that can do whatever PHP does!
<?php function addCity() { echo "Wow!"; } ?>
Think about it for a minute. We are virtually invoking a PHP function from Javascript code!
That over-simplified example was just to whet the appetite, a better explanation is on the Xajax site, have fun!
For some backend node processing, you can run JS script via shell and return the result to PHP via console.log
function executeNode($script)
{
return shell_exec('node -e \'eval(Buffer.from("'.base64_encode($script).'", "base64").toString())\'');
}
$jsCode = 'var a=1; var b=2; console.log(a+b);';
echo executeNode($jsCode);
I'm making a website which must be as lightweight as possible. There is a portion of javascript code I want to turn into a module using a separate file, so the code will be loaded after a certain onClick event.
I can successfully load the javascript code:
var myscript = document.createElement('script');
myscript.src = "modules/mymodule.js";
document.head.appendChild(myscript);
My problem is that my javascript code has some language-dependent variables that I generate php. Is there a way of running php on my javascript file prior to dynamic loading, or is it too late? Maybe using AJAX?
For people who look at this answer; please do not do this. Only run PHP files through the PHP interpreter. Doing this is an unnecessary security risk.
Depending on your web server, running PHP on JavaScript files is as simple as changing your webserver config.
Follow the instructions in this link: http://www.plus2net.com/php_tutorial/php5-iis7-configuration.php
However, when it prompts you to enter *.php, enter *.js.
By doing so, all your JavaScript files will be run through the PHP interpreter.
I think you must send your variable names and some date to your php doc.
then manipulate these variable names in your code then generate the right javascript code.
you should use AJAX to send your variable names .
You could just render it in PHP, then load it in as a JavaScript file.
MyScript.php
<?php
$number = 5;
echo "var number = {$number}"
?>
index.html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
function loadScript(url){
$.getScript( "MyScript.php", function( data, textStatus, jqxhr ) {
console.log( number ); // 5
});
}
</script>
</head>
</html>
I'm doing the internationalization of a PHP project.
in PHP I use the getttext() function and poedit program.
example:
<?php
echo gettext("Hello world");
?>
Hello World will be the key with the associated translated words:
It all works.
I haven't any idea how to translate the .js file with html function of JQUERY.
For example:
inside javascript file, I have
if(exchange=='mo'){
$(#hopen.title).html("NEW WORD");
}
the question is: How can I call the gettext function to "NEW WORD" and then use it with poedit program?
You don't want to call gettext / php from your javascript file every time you need a translation as that would mean you would have to make an ajax request to the server for each text.
Instead, you could generate an object in php with all the keys and translations that you need and send that to the browser and make it available as a global variable in javascript.
<?php
...
$needed_translations = array(
'Hello world' => gettext("Hello world")
...
);
?>
<script>
var needed_translations = <?php echo json_encode($needed_translations); ?>;
// or
window.needed_translations = <?php echo json_encode($needed_translations); ?>;
</script>
If your javascript file is loaded after this or your code is located in a document ready block, you will have access to this global variable and can use it wherever you want:
if(exchange=='mo'){
$(#hopen.title).html( needed_translations['Hello world'] );
}
This question already has answers here:
Can scripts be inserted with innerHTML?
(26 answers)
Closed 8 years ago.
Using Ajax, I'm calling a php file that contains javascript, but in this way, the javaScript doesn't work.
The main.html file is given here. It just uses Ajax for calling a php file called test1.php for updating all page at client.
<!DOCTYPE html>
<html>
<body>
<!-- run php file to fill the page -->
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.body.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","test1.php",true);
xmlhttp.send();
</script>
</body>
</html>
And the test1.php file is very simple test as follows:
<p id="demo">Hi there</p>
<script>
document.write("Yes! Hi there");
alert('Welcome!');
</script>
Now, just for checking that test1.php is ok, I put in the browser's url line:
localhost/test1.php
and everything works ok, the text of the html and js are displayed and an alert window with the word Welcome! is displayed.
But if I call the main page
localhost/main.html
Then only the html text 'Hi there' is displayed. The JS is ignored.
Anybody knows why is this?
Thanks
Krasimir Tsonev has a great solution that overcome all problems. His method doesn't need using eval, so no performance nor security problems exist. It allows you to set innerHTML string contains html with js and translate it immediately to an DOM element while also executes the js parts exist along the code. short ,simple, and works exactly as you want.
So in this case, the response from ajax is the src string which then translated to a DOM object according to Krasimir Tsonev and then you have it works with js parts that are executed.
var el = str2DomElement(xmlhttp.responseText);
document.body.innerHTML = el.innerHTML;
Enjoy his solution:
http://krasimirtsonev.com/blog/article/Convert-HTML-string-to-DOM-element
Important notes:
You need to wrap the target element with div tag
You need to wrap the src string with div tag.
If you write the src string directly and it includes js parts, please take attention to write the closing script tags correctly (with \ before /) as this is a string.
Here are 3 basic examples of what you can do with ajax & how you should do it:
Main html
js
function ajax(a,b,c){ // Url, Callback, just a placeholder
c=new XMLHttpRequest;
c.open('GET',a);
c.onload=b;
c.send()
}
function changeHTML(){
document.getElementById('mytext1').innerHTML=this.response;
}
function executeJS(){
(new Function(this.response))()
}
var array=[];
function loadJSON(){
array=JSON.parse(this.response);
updateFields();
}
function updateFields(){
for(var a=0,b;b=array[a];++a){
document.getElementById(b.id).textContent=b.data;
}
}
window.onload=function(){
ajax('getHTML.php',changeHTML);
ajax('getJS.php',executeJS);
ajax('getJSON.php',loadJSON);
// even if this works you should execute ajax sequentially
}
html
<div id="mytext1"></div>
<div id="mytext2"></div>
getHTML.php
<?php
echo "<div>i'm html</div>";
?>
getJS.php
<?php
echo "var a='hello';alert(a);";
?>
getJSON.php
<?php
$arr=array(array('id'=>'mytext2','data'=>'data'));
echo json_encode($arr);//json_decode
?>
if you want to execute a javascript function use the executeJS function and pass a valid javascript string.
There is no need for EVAL!
TIP:using json you can pass a function as data but as the parsing does not like the string function at the beginning a nice trick is to convert the javascript to base64 and back into a normal string with javascript with atob(base64) and have something like this:
function updateFields(){
for(var a=0,b;b=array[a];++a){
if(b.func){
(new Function(atob(b.func)))()
}else{
document.getElementById(b.id).textContent=b.data;
}
}
}
php
<?php
$arr=array(
array('id'=>'mytext2','data'=>'data'),
array('func'=>base64_encode("alert('jsonfunc')"))
);
echo json_encode($arr);//json_decode
?>
maybe there are some little errors ... i wrote that now. and can't check ajax atm.
if you have any questions just ask !!
I want to give you one advice that insted use of javascript you can use jquery ajax it will be easy and latest thing for ajax.
You can use $.ajax function. You can use json easily with this function
When you make an AJAX call you contact to a server url. If your url is, as in this case, a php page, it will execute on the server and return to your AJAX call the HTML that it produces... now you can play with that HTML and manage it or publish into your current's page DOM.
-AJAX is a server call that executes server code.
-A script tag embeded on a php page is HTML that will execute the code it contains on client when parsed and executed by a browser.
So... your code isn't executing because it's never being called... the response to your AJAX call will be exactly
<p id="demo">Hi there</p>
<script>
document.write("Yes! Hi there");
alert('Welcome!');
</script>
The php page executes and return that to your current page as text/html.
If you want to execute client code from your javascript you should have it on the same .js file or in another one included, but if you include it on a server page you'll need to redirect your browser to that page, if you call it with AJAX the code won't execute as the client browser won't parse it.