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?
-
3You cannot do it like that. I suggest to use a micro web framework in python like Flask. Then you can relate directories to run codes and functions.aminrd– aminrd2020年01月07日 18:25:19 +00:00Commented Jan 7, 2020 at 18:25
-
Does this answer your question? Call Python function from JavaScript codeRobert Moskal– Robert Moskal2020年01月07日 18:36:47 +00:00Commented Jan 7, 2020 at 18:36
-
@RobertMoskal i have seen it before i post this question, my problem is a bit different.Abdel-Rahman– Abdel-Rahman2020年01月07日 18:41:45 +00:00Commented Jan 7, 2020 at 18:41
-
1Abdel, it's not different! Good luck.Robert Moskal– Robert Moskal2020年01月07日 19:45:02 +00:00Commented Jan 7, 2020 at 19:45
3 Answers 3
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.
Comments
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.
5 Comments
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.