How to run python function from javascript? - javascript

I have a problem in calling my python function from my javascript file.
I'm using a simple server with python3 -m http.server, so no actual backend..my javascripts are in the front end.
I have a python file called write.py it has a function that I want to execute from my javascript file
write.py file:
def save_vit(text,name):
f = open(name + ".xml", "w+")
f.write(text)
f.close()
the javascript part that i have tried:(but didn't work)
$.ajax({
type: "POST",
url: "write.py",
data: { text: xmlDoc,name: name}});
xmlDoc is a string that has an xml document.
name is a variable that has the name of the file for the python function.
So my question is, what am I missing to call write.py from my js file or how to call it if this approach is wrong?

You are using http.server to serve the content of a folder, as files, not to execute them, so in the best case scenario, http.server will respond with the content of the write.py file instead of executing it.
You need to create a webserver that has a endpoint where the code of write.py is integrated.

You can't send a POST http request to run a python script.
You need to have the python script running on a server, that is able to take restful API calls, to run the script and return a value.
For example, you can run a small flask app that takes in your POST route, which runs a script and returns the value of the script back to the client that accessed the POST route.

Python is running on the server side ... JavaScript is running on the client side.
So, the only way for JavaScript to ask for a Python routine to be run is through an asynchronous AJAX request which you will have to build.

Related

Store result of a curl request / api call into a javascript file

I am able to successfully make an api call using a curl request using the command line.
curl -D - "https://api.hostsite.../"
However, I would like to take the returned data and be able to manipulate it in a .js file.
It works if I copy and paste the data into the file but would like to access the data just by running the .js file so that I can make multiple requests more easily.
I tried to using an ajax call but was wondering if there was an easier way I could do this without configuring the server and enabling CORS, which I was having some difficulty doing.
Well, if the API you are using doesn't support CORS (You can't do it yourself, the API has to support it because CORS is added in the headers of the response), you can use an intermediate language to make the curl request. (E.g. PHP)
From a Javascript file you can make a AJAX request to the PHP file containing the curl request. You just need to 'echo' the response from your PHP file and voilĂ , you get the response in your Javascript.
If you need more detailed information or help with the implementation please say something.
Hope this helps.
I got the desired result by using a bash script to populate the curl request data into a JSON file.
#script.sh
curl "https://data-api" > file-name.JSON
curl "https://data-api" >> file-name.json
node project/calculate.js
And then have the bash script run the .js file which reads the data from the JSON files.
$ ./script.sh

GET return value from Python via Javascript Ajax

I'm trying to write a Javascript program which can get the return value of my Python program, I'm using Ajax. The connect between Js and Python succeeded, but when I use alert() function in Javascript to show what I got, It shows that it is always the whole Python code, not the return value I want. I tried several different Python programs, the returns are always the Python program itself. I need to get the return value, ({"a":"15","b":"17"} in this example).
Here is the Ajax part in Javascript:
$.ajax({
type: "get",
url: "http://localhost:8000/test.py",
data: {a:"15",b:"20"},
datatype: "json",
success: function(response){
var output = response;
alert(output);
//var getvalue = output.startdate;
//var xxx = parseInt(getvalue);
}
})
Here is the Python program:
import cgi, cgitb
import json
import sys
def TryAgain():
data = cgi.FieldStorage()
output = {"a":"15","b":"17"}
return output
Here is the running result on website:
So, it looks like the problem here is that you aren't actually serving python code, but rather the file where that code resides. Your server needs another layer sitting between the code and the request that lets it understand how to translate the request into a specific function to run.
Typically, the way python users handle this is by integrating their server code into a web framework like Flask or Pyramid.
If you're also using a webserver for HTML content (which I assume you are, given that the file was reachable at all), you may need to additionally investigate using one more layer, that tells the webserver when to send things to your web framework rather than trying to service them itself. This layer is called WSGI, and most web frameworks will have specific guides with instructions on how to implement WSGI for your particular constellation of technologies.

Call Python Script from Javascript

I am on a dreamhost server and have some HTML that calls some javascript when a button is pressed. I am trying to call a python script when this button is tapped.
First off, to my knowledge as I am on a shared host I cannot use AJAX as it is not supported, so I need to do this without AJAX. Right now I am trying to do a XMLHttpRequest which is working.
I also realize doing an XMLHttpRequest is not the best way since the files are both on the server there must be a way to just call the file directly?
So if someone call tell me how to call it directly or help me fix this error in the browser console that would be great.
Thanks for the help
EDIT
I have an HTML file when a user taps a button on this file it calls some javascript that is in the HTML file. This javascript currently makes a POST Request, to a python script that is on the same server and the HTML file.
What I want instead of making a post request to the python file that is on the server, I want to just directly call the python file, from the javascript that runs, when the button the clicked in the HTML file.
Both the HTML file which contains the javascript and the python file are on the same server. And I don't want the python to run in the browser, I want it to run in the background on the server.
How can I use the Javascript to call this python file?
As far as I understand your question what you are looking to do is called a "remote procedure call", or some sort of Service Oriented Architecture (SOA).
You are on a right track in making a POST request to the server.
You can setup a middleware like flask, or cherrypy to run the script when you send a GET, PUT, POST ... request. And inside of the middleware controller you can call your script.
Basically you have started to create a RESTful api, and its a pretty standard way these days to run logic on the backend.
Some examples of different frameworks for doing url routing:
Python:
CherryPy: http://docs.cherrypy.org/en/latest/tutorials.html#tutorial-9-data-is-all-my-life
Flask: http://flask.pocoo.org/docs/0.10/quickstart/
a longer list of lower level python: http://wsgi.readthedocs.org/en/latest/libraries.html
NodeJs:
Express: http://expressjs.com/guide/routing.html
Koa: https://github.com/koajs/route
Hapi: http://hapijs.com/tutorials/routing
Also very good is this question: JSON, REST, SOAP, WSDL, and SOA: How do they all link together
Another way that you could do this from the browser would be to use sockets, which opens a connection between the client and the server.
Inside the javscript you could use socketio:
<script src='/socket.io/socket.io.js'></script>
<script>
var socket = io();
socket.connect('http://localhost:8000')
socket.emit('run_a_script_event', {arg1: 'hello', arg2: 'world'});
</script>
And in your python code you could use the socketio client for python (https://pypi.python.org/pypi/socketIO-client):
from your_module import thescript
from socketIO_client import SocketIO, LoggingNamespace
def run_a_script(*args):
print('arg1 and arg2', args)
thescript()
socketIO = SocketIO('localhost', 8000, LoggingNamespace)
socketIO.on('run_a_script_event', run_a_script)
Looks like there is also a version specifically for flask: https://flask-socketio.readthedocs.org/en/latest/
Or you could run the python directly in the browser by converting it to javascript with a transpiler:
http://www.skulpt.org/
Or you could use node javascript to spawn a child process which runs the python script:
https://stackoverflow.com/a/20973067/2026508
Or you can import the python script into node like:
Use of node-python to execute python scripts from web application hosted under python?

$.getJSON() call from express static html file doesn't get data

I am using the express module as the basis for my node.js server, and set up a static middleware as follows:
self.app.use(express.static(__dirname));
Within the root folder I have an html file that includes the following url to a php script on my remote server (completely different to the server hosting the node.js application) that returns jsonp data (having converted from xml data from the dataprovider):
var strURL = 'http://example.com/jsonp.php?callback=?&url=http://dataprovider.com/1.4/?arg1=xyz;arg2=abc';
And then a jquery getJSON call to actually get the json data:
$.getJSON(
strURL,
function (jsondata) {
// do some stuff with the json data
}
);
But when I load the html file that is being served from the static node.js folder, no data is returned... the code never reaches the jsondata function.
However, loading the very same html file placed on a "normal" server, the data is fetched just fine, and also if I load the strURL directly, the data is returned OK.
I suspect that this has something to do with cross domain issues, but for the life of me I can't get the page to work within the static node.js server using express. I've tried various solutions out there, but am now thoroughly confused and frustrated!
Any help would be welcome.
Have had cross domain issues with JSON in the past and got round them by using JSONP. There is a good explanation and tutorial at:
http://json-jsonp-tutorial.craic.com/index.html

Executing AJAX written in a PHP script with cron

I've written a PHP script that reads data from Facebook user's profile and sends it to my server through AJAX. This script needs to run in intervals, so I added a cron. All the PHP functions and interactions with databases through MySQL are working with cron. But AJAX is not. I know it's (JavaScript) a client-side script, but is there any other way? How I can execute JavaScript (AJAX) written in a file through cron.
Ajax is a client-side technology you cannot run that in PHP console.
Ajax calls consist of an API (application programming interface). The API is the system of calls through which a client (the browser) communicates with a server (the server).
In your case, the client is the computer on which the PHP script is running and the server is your server. If you can replicate the API used in JavaScript in PHP then you are away on hack.
For example, suppose the sever you were communicating with had a service called "postupdate.php" and it took one value called "update", the API call might look like this in JavaScript:
<script type="text/javascript">
var response;
$.ajax({
url: "http://www.example.com/postupdate.php?update=This_is_my_update"
}).success(function(text) {
response = text;
});
</script>
The same API call might look like this in PHP:
<?php
$response = file_get_contents("http://www.example.com/postupdate.php?update=This_is_my_update")
?>
This example assumes the API uses the HTTP GET method. APIs that use HTTP POST methods are more complicated but can be used in PHP as well.

Categories