I believe it is possible to execute a java script function within PHP, but will it then remain server side as opposed to client side? Can I, within PHP, call a .js function, passing it some args, and have it return to the PHP that called it?
A script I want to use returns XML, and I want to get the user inputs using PHP, pass them to the .js function residing on the server , then take the returned xml and parse it back in the PHP part.
I ask because I see people commenting that because .js is client side and PHP is server side, they don't get along. I was hoping that by executing the .js function in the PHP, I could spoof the .js call as coming from the local machine (the server).
Thanks for any information!
You cannot call JavaScript from within PHP itself. PHP is not a JavaScript engine.
However, there is a PECL Extension for interfacing with V8:
And you can interface with a (serverside) JavaScript engine. Have a look at node.js and
You could if you found a server-side Javascript interpreter that you could call out to. I haven't used PHPJS (http://phpjs.berlios.de/) but it might work.
It sounds like your better bet is to replace the js code, because what you're doing just sounds like a bad idea.
I think bpeterson nailed it. But if you are uncomfortable with AJAX, or just need a little more specifics.
First - Put an action on a button (form submit or otherwise). action="javascript:yourJsFunc()". This element is likely being rendered thru echos on your PHP, or just written statically.
Next - Get the parameters you need. I'd suggest jQuery or DOM methods, ie. $('#blah') or document.getElementById('blah').val();
Then - Set hidden inputs to store your response, force a submit or do ajax request. You are in PHP with your values!
function yourJsFunc()
{
var arg1 = $('#arg1').val //or equivalent DOM method
var arg2...
//serialize these if necessary
var yourXML = outsideJSFunction(arg1, arg2, etc);
$('#invisibleDiv').html('<form id="yourForm" method="POST"><input type="hidden" name="x" val="'+yourXML+'" /></form>');
$('#yourForm').submit();
//ALTERNATIVELY $.get("other.php", {myXml : yourXml}, function() {//whatever});
}
This is really not as difficult as you're making it seem.
FYI, there's a relatively little-known solution for AJAX via PHP called XAJAX . It probably wouldn't help you out too much in this situation, but it allows you to make AJAX calls on PHP functions. While it's true that PHP doesn't have a javascript interpreter, XAJAX and Jquery's Ajax are excellent ways for the front end code to interact with the server-side functionality.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.