php: writing a script function - javascript

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>')

Related

Call a javascript function from php [duplicate]

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);

Running Javascript+PHP Form Another File

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.

A method to pass a variable to Javascript currently run in the header

Please excuse me ignorance, I'm completely new to Javascript.
I have this code that is currently run in the header, however I need to pass it $_GET variables before it runs.
jQuery(document).ready(function() {
refresh();
jQuery('#bittrex-price').load('http://<site>/realtime/bittrex-realtime.php?symbol=ltc');
jQuery('#mintpal-price').load('http://<site>/realtime/mintpal-realtime.php?symbol=ltc');
});
function refresh() {
setTimeout( function() {
jQuery('#bittrex-price').fadeOut('slow').load('http://<site>/realtime/bittrex-realtime.php?symbol=ltc').fadeIn('slow');
jQuery('#mintpal-price').fadeOut('slow').load('http://<site>/realtime/mintpal-realtime.php?symbol?ltc').fadeIn('slow');
refresh();
}, 10000);
}
It's pretty simple, all it does is pull the latest price from another PHP script.
I need to append a $_GET variable to the URL as current I have no way to change the ?symbol=ltc depending on which page the user is visiting. Because Wordpress is being awkward, I've had to save this function in a .js file and add a hook in functions.php otherwise it won't load at all. Ideally, I'd like to be able to run the function in the body so I can modify, but I can't get that to work either :/
I hope this makes sense, I'm open to any suggestions as I'm clearly missing the point somewhere here.
Thanks
You need to use the language that is building the web page to output some javascript for use in your functions.
Thus, if you're using PHP to build your page you could do something like this in the <head> section of your page:
<?php
print '<script>';
print 'var symbol = ' . $_GET['your_get_variable'] . ';';
print '</script>';
?>
Then, in your later javascript code you have your GET variable string stored in 'symbol' and can use it however you like.
The 'your_get_variable' is what is coming in via the query string in the URL that got you to the current page. Just make sure you put this code above where you want to use 'symbol' in your later javascript.
Also, It's not really a good idea to use $_GET data directly like that without some validation, but I'm just keeping the example clean.

JavaScript in php file doesn't work when php file is called using Ajax [duplicate]

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.

Set a PHP Variable through jQuery function

Hey guys i have a system where when you click one div it loads up one div and the other loads up another but instead of this i'm trying to get it to load up content based off a variable to consolidate things betters
So the main question it, how do i set a PHP through a jQuery function e.g.
<script>
$(document).ready(function () {
$('.redboothApp').click(function(){
<SET VARIABLE>
$('.whiter').fadeIn(250);
});
});
</script>
So then in the PHP it will be something like:-
<?php
if (($appLaunched) == 0) {
echo "0";
}
else if (($appLaunched) == 1) {
echo "1";
}
?>
Thank you in advance, help would be greatly appreciated :)
You can't set a PHP variable with JavaScript. PHP is parsed and executed on the server and then outputs the data to the browser. Once output to the browser any JavaScript is run. It can't then "talk back" to the PHP that processed it. That would be like Harry Potter giving advice to J.K. Rowling on how best to progress the story.
The closest you can get to this kind of behaviour is with an AJAX call -- using JavaScript to determine the data to send to a different PHP script, potentially with return data which can then be processed by JavaScript. However, I don't believe that this is the sort of thing you're looking for.

Categories

Resources