Reputation: 8412
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)
Upvotes: 1
Views: 904
Reputation: 413702
The HTTP request you're performing happens on its own time. The call to httprequest.send()
starts the operation, but that function call returns almost immediately, and definitely before the remote server has responded. This asynchronous behavior is a basic fact of life in JavaScript environments.
The whole reason for the "onload" callback is to make it possible for you to write code that happens when the HTTP request actually completes. The browser will invoke that function with the results when the results become available. That might be in 100 milliseconds, or 10 seconds; it all depends on the server and the network.
Upvotes: 1