How to pass data to python scripts from JavaScript? - javascript

Here is the HTML file where in scripts portion I made an ajax request to pass some string to python function.
var status = "hello there!!!"
$.ajax({
url: "../SCRIPTS/cond.py",
type: 'POST',
data: {
'status': status
},
success: function (data) {
location.reload(true)
}
});
Here in url I set the path of python scripts. Python file where I want to fetch the requested data from JS and print it.
def main():
#
if __name__ == "__main__":
main()
def test(request):
print(request)
Note: Here I am not using any framework. Just pure HTML, JS and Python file.

Your backend logic(python script in this case) must be hosted on a http server. An "ajax" request is an http request. You can not POST something to a file on the local file system. Are you running your script on a server? If so, you should be able to access it via a http(s):// type URL.

Related

Send POST request from JavasScript to Sinatra endpoint

so I have a javascript file that saves a specific value in a variable send that I need to send to my ruby routes file through a POST request. I'm a little confused if I can do this since what I have does not seem to work. I'm using the MVC structure so my routes file is saved in my controllers folder.
In my JS file, I have the following:
var send = "test"`
$.ajax({
url : window.location.href + "senddata/",
type : ",
data : { send: send },
}).done(function(response) {
alert('1');
}).fail(function (error) {
alert('2');
});
In my Ruby file, I'm not sure what to do to be able to receive this data? I know I need to do #variable = params[:send] but not sure from there. I'm using Sinatra.
My ruby code is as follows:
post '/senddata/' do
flash[:success] = "Reached"
end

How to send a single string to python function from ajax query

Context: I am using JavaScript to send a string as a parameter to a python function over the flask.
But I always get "the missing 1 parameter error" on the python side.
This is what my Ajax query looks like:
$.ajax({
url : 'ListMaker',
data: 'Q1',
success: function(data) {
//does something
}
});
This is what my python function looks like:
#app.route("/ListMaker",methods=["POST","GET"])
def ListMaker(text):
#make it a string just incase
quarter=str(text)
//do things with string
Any other similar questions I can find online, only talk about issues with Ajax and don't really cover the python side. In my case, the function is clearly being called, but it claims to receive no data to work with.
Am I sending the data wrongly from the Ajax side? Or am I parsing it wrongly on the python side?
Clarification for NoneType error from the comments below:
I am sending over:
data: JSON.stringify({"letter": "Q", "value": "25%"})
I am receiving it on the python side like so:
data=request.get_json()
letter=data["letter"]
value=data["value"]
The parameters in a Flask route are for variables in the path, called "variable rules" in Flask:
#app.route("/ListMaker/<text>", methods=["POST", "GET"])
def ListMaker(text):
...
As jQuery Ajax requests are GET by default, your data will be converted to a query string, in this case /ListMaker?Q1. You can access the query string in Flask with flask.request.args.
However, query strings are key-value, and you are only supplying a key, which will correspond to the Python dict {'Q1': ''}. You should either set the Ajax data to a string like quarter=Q1, or use an object:
$.ajax({
url : 'ListMaker',
data: {'quarter': 'Q1'}, // or 'quarter=Q1'
success: function(data) {
//does something
}
});
Then you will be able to access it in Flask:
#app.route("/ListMaker", methods=["POST", "GET"])
def ListMaker(): # no parameters needed
quarter = flask.request.args["quarter"]
# quarter == "Q1"
If you want to use a POST request, set method: 'POST' in the Ajax-call, and use flask.request.get_data() or flask.request.get_json() on the Flask side.

Ajax call to Python script. What am I missing?

What am I doing wrong here please. I want to run an very basic python script on the server side and the get the return value to the client side (ie javascript)
My python script is:
// Hello.py
--------------------------
import sys
def hello(str):
print('Hello ' + str)
return 1
if __name__ == '__main__':
hello(*sys.argv[1:])
and my Ajax call:
function getAjax(url, data){
return $.ajax({
type: 'POST',
url : url,
data: data,
success: function(response) {
return response;
}
});
}
getAjax("./scripts/hello.py", 'John').done(function(response){
console.log(response);
});
When I run getAjax the console.log(response) statement just prints the text (ie code) in my Python script. What is the step I am missing here please?
You need a server for link an http request from your browser on a specific port (default 80) of your network target and get the reponse of a specific script, the most simple usage for local tests like this in python is to use something like simplehttpserver: https://docs.python.org/2/library/simplehttpserver.html

How to send a file uploaded by javascript and get it received in a flask app and send it as post request to another server?

When i try to send a post request from flask using the file, which is received via the ajax request from client side, I am getting an exception:'too many values to unpack (expected 2)
I have a client side app which uploads a file(Javascript).
I have my server code which acts as a proxy which deals with all external server calls. The uploaded file gets send to this server as a post request from client side.
Now i need to send this file received in my server to an external server as a post request using requests module in python.
I am stuck with an exception when i am doing step 3.
I am not sure if it is the right way to post such files as i am new to flask. Please give some inputs which might help.
Client side code
$('input[type="file"]').change(function (e) {
var formData = new FormData(e.target.files[0]);
var fileName = e.target.files[0].name;
var fileType = e.target.name;
var settings = {
"async": true,
"crossDomain": true,
"url": "/upload?file_name="+fileName+"&file_type="+fileType,
"method": "POST",
"contentType": false,
"cache": false,
"processData": false,
"data": formData
};
$.ajax(settings).done(function (response) {
console.log(response);
});
});
Flask code
#app.route('/upload', methods=['GET','POST'])
def uploadToExternalServer():
if request.method == "POST":
try:
file_content=request.files['file']
file_type= request.args.get('file_type')
file_name= request.args.get('file_name')
url="url to post with params"
response = requests.post(url, auth=('usr', 'pwd!'),files=file_content)
return r
except Exception as e:
logging.info(e.args[0])
Expected:
Should be able to successfully post the file to the external server
Actual:
Getting an exception at post request as :'too many values to unpack (expected 2)
Check the documentation of Requests
I think your problem is that you are trying to do your post passing the file like an object, and the param expects an dictionary.
files – (optional) Dictionary of 'name': file-like-objects (or {'name': file-tuple}) for multipart encoding upload. file-tuple can be a 2-tuple ('filename', fileobj), 3-tuple ('filename', fileobj, 'content_type') or a 4-tuple ('filename', fileobj, 'content_type', custom_headers), where 'content-type' is a string defining the content type of the given file and custom_headers a dict-like object containing additional headers to add for the file.

Calling a Python script from Javascript, both local files

I'm trying to run a python script from a local javascript file (part of a locally running HTML/javascript program).
I've been googling this for hours and found a lot of solutions, none of which actually work for me.
Here is the javascript:
$.ajax({
type: "POST",
url: "test.py",
data: { param: " "}
}).done(function( o ) {
alert("OK");
});
The test.py file is in the same folder as the script/html file.
here is the script:
#!/usr/bin/python
import os
filepath = os.getcwd()
def MakeFile(file_name):
temp_path = filepath + file_name
with open(file_name, 'w') as f:
f.write('''\
def print_success():
print "sucesss"
''')
print 'Execution completed.'
MakeFile("bla.txt");
It works fine when run normally.
On my Firefox console I get a "not well formed" error and the script doesn't create a file. However, I can see that Firefox does fetch the script, as I can view it in my browser by clicking the file name.
In order for the python script to execute it has to be deployed by a web server that supports it via CGI or WSGI, etc.
Check out the docs here: webservers
There are three problems with your code.
First, when you call $.ajax(), it tries to parse the response as either JSON or HTML. To prevent it, use dataType: "text".
$.ajax({
type: "POST",
url: "111212.py",
data: { param: " "},
dataType: "text"
}).done(function( o ) {
alert("OK");
});
Second, fetching a local file from javascript may violate the Same Origin Policy, depending on the browser. See: Origin null is not allowed by Access-Control-Allow-Origin
An most important, fetching does not execute a file, it just reads it and returns as a string.
So apparently, as has been pointed out, this can't be done, not like this. So I'm going to start a simple CGI python sever to server the HTML file, and execute the script. I've tested it and it works great!

Categories

Resources