Iceman
Iceman

Reputation: 385

How to receive POST data in python when using XMLHttpRequest()

I have two questions regarding receiving of data when using XMLHttpRequest(). Client side is in javascript. Server side is in python.

  1. How do I receive/process data on the python side ?
  2. How do I respond back to HTTP request?

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.

Upvotes: 8

Views: 7259

Answers (1)

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52163

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)

Upvotes: 1

Related Questions