I have two questions regarding receiving of data when using XMLHttpRequest(). Client side is in javascript. Server side is in python.
Client side
var http = new XMLHttpRequest();
var url = "receive_data.cgi";
var params = JSON.stringify(inventory_json);
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {
//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
UPDATE: I know i should use cgi.FieldStorage() but how exactly ?My attempt ended with me getting a Server error for the post request.
XMLHTTPRequest object is an API which is used for fetching data from the server. XMLHTTPRequest is basically used in Ajax programming. It retrieve any type of data such as json, xml, text etc. It request for data in background and update the page without reloading page on client side.
setRequestHeader('Content-Type', 'application/json') ; is added 1 line above or below the Accept header, the method used changes to OPTIONS, the Accept header changes to "text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8" and the Content-Type header disappears as if it wasn't seen.
The XMLHttpRequest method send() sends the request to the server. If the request is asynchronous (which is the default), this method returns as soon as the request is sent and the result is delivered using events. If the request is synchronous, this method doesn't return until the response has arrived.
You don't necessarily use cgi.FieldStorage
to handle POST data sent by an AJAX request. It is just the same as receiving a normal POST request, which means you need to get the request's body and process that.
import SimpleHTTPServer
import json
class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_POST(self):
content_length = int(self.headers.getheader('content-length'))
body = self.rfile.read(content_length)
try:
result = json.loads(body, encoding='utf-8')
# process result as a normal python dictionary
...
self.wfile.write('Request has been processed.')
except Exception as exc:
self.wfile.write('Request has failed to process. Error: %s', exc.message)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With