Question

Hi I'm trying to get an ajax response from a wsgi server behind nginx (if that matters). I think I'm having issues reading the request as it would seem the variable request_body_size is always 0; I get a return value of "No Request" in the alert box when I would like to see "test string".

I cant find many docs on this or examples of this working, so if anyone knows how to fix this I would be grateful.

I have this python code in the WSGI script:

import os, sys
from cgi import parse_qs

def application(environ, start_response):

    try:
        request_body_size = int(environ.get('CONTENT_LENGTH', 0))
    except (ValueError):
        request_body_size = 0

    context = {}
    if request_body_size != 0:
        request_body = environ['wsgi.input'].read(request_body_size)
        output = parse_qs(request_body)
    else:
        output = "No request" 


    status = '200 OK'
    response_headers = [('Content-type', 'text/html'),('Content-Length', str(len(output)))]
    start_response(status, response_headers)
    return [output]

and this is the js making the request (jquery):

function test_request()
{
    var test_string = "test string";
    $.ajax({
        type: 'GET',
        url:"/ajax", 
        data: test_string, 
        success:function(result){alert(result)}}
    );
}
Was it helpful?

Solution

The ajax() method converts the 'data' value to a QUERY_STRING when the method is GET. Using POST should address the issue (or you can read environ['QUERY_STRING'])

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top