I'd like to send some (JSON, for now) data to a Python script and access the result. After trying and failing to do this own my own, I came across two examples here on SO. I have been able to make neither work.
pythonAjaxTest.html
:
...
<script>
$(function(){
$('#ajaxButton').click(function(){
alert("Ajaxing...");
$.ajax({
url: "ajaxTest.py", //equivalently, replace with "saveList.py"
type: "POST",
dataType: "json",
data: JSON.stringify({
"param" : { "hello" : "world" }
}),
success: function(response) {
alert(response.responseText);
}, error: function(response) {
alert(response.responseText);
}
});
});
});
</script>
...
ajaxTest.py
:
#!/usr/bin/env python
import sys
import json
import cgi
fs = cgi.FieldStorage()
sys.stdout.write("Content-Type: application/json")
sys.stdout.write("\n")
sys.stdout.write("\n")
result = {}
result['success'] = True
result['message'] = "The command Completed Successfully"
result['keys'] = ",".join(fs.keys())
d = {}
for k in fs.keys():
d[k] = fs.getvalue(k)
result['data'] = d
sys.stdout.write(json.dumps(result,indent=1))
sys.stdout.write("\n")
sys.stdout.close()
saveList.py
:
#!/usr/bin/python
import sys, json
result = {'success':'true','message':'The Command Completed Successfully'};
myjson = json.load(sys.stdin)
# Do something with 'myjson' object
print 'Content-Type: application/json\n\n'
print json.dumps(result) # or "json.dump(result, sys.stdout)"
With both of these, I get a 400
error in the console and following responseText
:
<?xml version=‘1.0’ encoding ‘UTF-8’?><Error><Code>InvalidArgument</Code><Message>Invalid argument.</Message><Details>POST object expects Content-Type multipart/form-data</Details></Error>
Given that I'm using basically the exact same code as in each of the accepted answers to these two questions, I'm not sure what I'm doing wrong. Is this simply a Google Cloud issue? All my source files are together in a bucket. (1, 2.)
I'm running these scripts with a n1-standard-1 (1 vCPU, 3.75 GB memory)
VM.
The desired behavior: I want to make a successful Ajax request to these Python files and have the result—some result—returned. I'm looking for exactly the behavior described by the answerers of the two questions I linked to.
Specific problem or error: The Ajax fails. The error is a 400
and the text is above.
Shortest code necessary: The code I have included is perhaps somewhat long, but I've included because I want to include exactly what was in other accepted answers. (Problem statement:) How I can make an Ajax request to Python files that work in other circumstances work on Google Cloud?
Currently working through Martijn's answer...