I have an html test file with the following
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<body>
<script type="text/javascript">
var httprequest=new XMLHttpRequest();
httprequest.open("POST","hello.cgi",true);
httprequest.onload=function(){
if(httprequest.status==200){
alert("");
}// end of if
}//end of onload
var content={"hello":"world"};
httprequest.send(JSON.stringify(content));
alert(httprequest.responseText)
</script
</body>
</html>
</doctype>
In this scenario I am trying to send the data {"hello":"world"}; to a python cgi script
This is my python script that works well with data submitted from a <form> html tag
#!/usr/bin/python
try:
import sys
import cgi
import traceback
print("Content-type: text/html\n\n")
print "<h1>YES</h1>"
formData = cgi.FieldStorage()
print(formData)
print(s)
except Exception as e:
print(e.message)
print(traceback.print_exc())
When I send the data {"hello":"world"}, my browser alert box shows no data returned from the cgi script.
As reflected in the cgi script, I am trying to print "YES" and print the data that was sent from javascript.
I have found several questions relating to use of $.ajax to do this but haven't come across a method using XMLHttpRequest()
Question
How can I send data to a python cgi script for processing from my browser using pure javascript (no jquery)
alert()happens long before the HTTP request has completed. It's an asynchronous operation.