O. Barinov O. Barinov - 18 days ago 8
Ajax Question

JS array is not send to python script with AJAX

An idea is to send

JS
array which contains of HTML element ids to python script using
AJAX
. I have gone through multiple examples, on Stackoverflow as well but none of them worked so far.

My
JS
function is:

function callpc1() {
var pcimages = document.querySelectorAll('.pcpics');
test = [];
test[0] = pcimages[0].id;
test[1] = pcimages[1].id;
test[2] = pcimages[2].id;
$.ajax({
type: "POST",
url: "/~.../pcmove1.py",
data: {
test:test
},
});
}


Problem is python script gets no array data and variable remains empty on python side
On python side I use
getvalue
method. I assume an error is with
data:
definition. And I would to avoid using
JSON

Please give a hint of what is wrongly defined here?

Edit




Code on python side

import cgi
page = cgi.FieldStorage()
listed = page.getvalue('test', "unsuccess")
results = open("test.txt", "aw")
results.write (listed)
results.close()

Answer

Python's cgi module does processing that isn't appropriate for submitted JSON data. Specifically, content of a POST request is provided to a CGI module on stdin and cgi.FieldStorage() reads that and tries to convert it into something useful but assumes a normal form submission. Other data is provided as environment variables.

Adjusting your example, you may be able to get your post data as a Python object like this:

import sys, os
import json

length = os.environ["CONTENT_LENGTH"]
raw = sys.stdin.read(length)
data = json.loads(raw)
# Now we have a Python object representing the JSON data

# Convert the Python object back into a JSON formatted string
# and save to file
results = open("test.txt", "aw")
results.write(json.dumps(data))
results.close()
Comments