Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 601
Iceman Avatar asked Feb 05 '15 22:02

Iceman


People also ask

What type of data can you get using the XMLHttpRequest object?

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.

How can request content type be set to XML via XMLHttpRequest?

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.

How do I send a request body in XMLHttpRequest?

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.


1 Answers

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)
like image 105
Ozgur Vatansever Avatar answered Oct 19 '22 17:10

Ozgur Vatansever