I have a JavaScript file on my server that contains a function. I would like to develop a REST Api to connect to this server, run the JavaScript function and send back the output.
Is it possible to call a JavaScript function from a php file?
I read this but it doesn't answer my question, because my js file is hosted on the same server as the php file.
Is the V8Js extensions what I am looking for?
Edit
The js function looks like this:
function (line, userWeight, weightunit){
//logic is here
var computed = {
userLengthFtin: userLengthFtin,
userLevel: userLevel,
proId: line['id'],
proLengthFeetin: proLengthFeetin,
proThick: proThickFtin,
weightunit: weightunit
};
return computed;
}
Is it possible to call a javascript function from a php file ?
You would need to hand things over to some other software which can execute JS. This might be through shelling out or it might be though a library such as Selenium or the V8js library you found.
Whatever you choose, it would need to be able to handle the particular needs of the JS (e.g. if the JS expects to be embedded in a webpage with access to a DOM and all the APIs provided by a web browser, then you couldn't simply run it with Node.js).
It would probably be simpler to rewrite the function in PHP.
Related
I have a question that has been asked several times here and other places around the internet*, but answers I've seen are incomplete or ineffective.
I would like to have a JavaScript function runPy() that, upon being called (in a browser, via a button-click for instance), will execute a Python script in my server that we'll call test.py.
Let's say that test.py is simply designed to create a text file and write in it 'hello world'
Python
f = open('test.txt', 'w+')
f.write('hello world')
Based on other answers, I have pieced together the following JavaScript/jQuery function:
JavaScript
function runPy() {
$.ajax({
type:'POST',
url:'test.py',
success: function(data) {
console.log(data)
};
});
}
Now, this is of course incorrect. As one might expect, rather than running the Python script, it prints to the console the contents of the script:
Console
f = open('test.txt', 'w+')
f.write('hello world')
How would I go about editing my JavaScript (and/or Python) to achieve the functionality I would like? In a perfect world, I would like to avoid importing any new dependencies (I've seen some answers dependent on Flask or Django) but of course beggars can't be choosers.
Additionally, if I will allow myself to get greedy, it would be very nice to be able to pass arguments to the Python script as well, or even use JavaScript to call a specific function in the Python script, and have the results passed back to the client-side JavaScript.
*Similar Questions
Call python function from JS
how to call python script from javascript?
Run Python scripts from JavaScript functions
You're going on the right path.
But, here's why the POST isn't working. Except for HTML filetype, making a POST call to fetch a static file on the server (i.e. random.js, random.css etc) will print the raw file content.
In this scenario, you'll need to handle this on the server-side backend code. I don't know which backend framework you're using but here are some articles that can help you with this:
NodeJS: https://medium.com/swlh/run-python-script-from-node-js-and-send-data-to-browser-15677fcf199f
.NET: https://medium.com/better-programming/running-python-script-from-c-and-working-with-the-results-843e68d230e5
Java: Running a .py file from Java
UPDATE!!: Due to the recent developments in the space of Web Development, it is now possible to run Python on the Client-side through WebAssembly. Please find more instructions here: Pyodide
I have php file that is to be executed as cronjob, this php file contains some javascript.
I will explain the flow :
the Php is used to retrive some data(A LIST OF URLS) from DB.
For each URL Obtained, a Java script API is used.
THe result Obj returned from API contains data for each url.
The data is then sent back to as an AJAX Call for each url to a php file .
Can this be implemented Via CRON JOBS ?
OR
Is there any method to schedule javascript to run periodically, like cron for php?
UPDATE: i could manage the javascript call to API with PHP curl ,And the cron Job is getting executed perfectly. But i dont think it is the correct solution to this question may be Node.Js is the solution(i didnt test it yet).
You can't run Javascript in Cronjobs because Javascript is ran by browsers. I think you should take a look at curl in php to call an api instead.
http://www.php.net/manual/en/book.curl.php
You have to split the work: Cron the JS, Cron the PHP. In the middle, deliver one's results to another. Agree with phantomjs usage for JS execution (or casperJS-I prefer). Execute the JS, output to JSON as a file, read from the file using file_get_contents from PHP. And define these actions in two different cron jobs.
You can run Javascript via cron in a Javascript runtime like node.js: http://nodejs.org/
phantomjs is one possibility, see this thread wget + JavaScript?
Otherwise you could run Node.js on your server to execute JavaScript in a CLI type environment but mixing node.js and PHP could become complicated.
you can schedule javascript with cron by using Node.js
I have a question about compiling server side functions in PHP with Ajax. I am trying to understand what happens when multiple asynchronous calls are made to the same server side script.
Lets say that I have the following php script - "msg.php":
<?php
function msg(){
$list1 = "hello world";
return $list1;
}
echo json_encode(msg());
?>
and call Ajax JQuery like this:
function get_msg() {
$.get("msg.php", function(data){console.log(JSON.parse(data));}) }
with a button in html:
input type="button" onclick="console.log(get_msg());" value="Submit" class="btn btn-info"
Assuming that everything works I am trying to understand the following:
Does the server recompile the "msg" php function each time a user clicks the button? Does it (or can it?) manage this by user? How about by session?
After multiple clicks by different users does the server destroy the "msg" function after each request? Can I save multiple versions of the same function in memory for later use? If so is it possible to reconcile the different versions?
Is there a way to pre-compile a single php function for all Ajax requests?
Is there a "proper" way to handle dynamic function calls on the server side?
I feel like recompiling it on the server side is wasteful but perhaps this is how things are supposed to work.
PHP interprets code on each request. But there is OPcache:
OPcache improves PHP performance by storing precompiled script bytecode in shared memory, thereby removing the need for PHP to load and parse scripts on each request.
This extension is bundled with PHP 5.5.0 and later, and is available in PECL for PHP versions 5.2, 5.3 and 5.4.
You can find here on SO how to enable OPcache:
Add the following line to your php.ini:
zend_extension=/full/path/to/opcache.so (nix)
zend_extension=C:\path\to\php_opcache.dll (win)
... and much, much more!
I think what you're looking for is caching. PHP by default is a scripted language so if you need to reference something repeatedly it will be executed each time since its interpreted not compiled. Caching is a way around that.
There are a few ways I can think of to store this data for later use. One is cacheing in plain text. Write out your result to a text file and then reference that for later use, using the last modified date as a way to check for freshness. I'm not a big fan of this method because I think having extraneous files written to the server is messy. (just my opinion)
http://php.net/manual/en/function.file-put-contents.php
Thats the function you would use to store your result.
Another option is writing to a database for the results and then time stamping it so you can reference that for freshness. From there you could just use PDO or mysqli to retrieve the data. Then you could use a database cache to make the response time more performant.
Another option is just using something like OPCache to store the results of the function in memory on repeated calls. ( I don't have much experience in this though )
Hopefully that puts you in the right direction.
If I have a function written in Google Spreadsheets script editor that retrieves the data in the spreadsheet in JSON format, how can I access that function outside of the script editor in my own code? I want to access that JSON and manipulate it in my own code. Is there a way to do that using the Spreadsheets API? I format it in a specific way inside script editor so I can't just use the json-in-script provided. In the call (http://spreadsheets.google.com/feeds/feed/key/worksheet/public/basic?alt=json-in-script&callback=myFunc) there's a callback function for myFunc. Can I use the function I defined in the script editor to replace myFunc?
Following your comment that brings some details on your use case, there is a Google-Apps-Script feature specially designed to give access to some functions you wrote from within another script : is is called libraries and is fully described in the documentation.
EDIT, following 2cond comment:
Calling a GS function from a javascript (or any other language) script that is not a Google Script (GS) is not possible if you consider using it as a function...
but
what you can eventually do - depending on the data this function must handle - is to deploy a script as a webApp running as a service and call this service from your external app using the equivalent of an urlFetch (that's the service doing that in GS).
The service will have an url to which you can add parameters and it will return a result that you can use in your local app.
Of course this workflow has a few limitations and might quickly become complex but in many cases it is fully workable.
Note that the url you will have to use in the "versioned" one ending with .exec (Not sure this word is correct but I mean the published url that corresponds to a version of your script and not the ".dev" one that one can use to test a script in GS).
You'll find details about that in the documentation and on many other ressources, including SO. The url is typically something like this :
https://script.google.com/macros/s/AKfycbyw-2WtmF7wsd__________azjImbMWm5YrxB8/exec?someParameter=someValue&otherParam=otherVal // etc...
I need to be able to execute a shell command through javascript, similar to the php function "exec()". I understand that this may be impractical in javascript because of security reasons, but my javascript code is running on the server, and no clients have direct access to the file.
Users make a request to the server for some data, and the server-side javascript code is called. From the javascript file, I need to execute a program in order to gather data based on user input, then pass this data back.
If this isn't possible in vanilla Javascript, please point me towards a library or tool that can do this, preferably in javascript/frameworks on javascript.
JavaScript has no 'exec' function like PHP does. It's all because JavaScript runs on the client and don't have access to the server part.
However you can create PHP page and send AJAX requests to it to execute particular command.
ALTHOUGH, you need to be VERY, VERY and VERY cautious about which commands to run.
It's very dangerous to do like that. I don't advice you to do like that, however, it's possible.
Good luck!
If it's client side - You can't
If it's node.js:
var exec = require('child_process').exec;
child = exec("command", function (error, stdout, stderr)
{
// handle the output
});
This might be what you're looking for: https://github.com/arturadib/shelljs
Or, if you want to have direct access to commands, perhaps this will help: http://nodejs.org/api/child_process.html