sc28 sc28 -4 years ago 147
jQuery Question

Using data from Ajax in a python script

I'm trying to use a Python script to fill a PostgreSQL table with data received from an Ajax POST.

My Ajax command is:

function ajaxFct() {
$.ajax({
async: true,
type: "POST",
url: "/myDir/cgi-bin/send_array.py",
data: my_array,
dataType: "html",
success : function(data) {
document.getElementById("ajaxAnchor").innerHTML = "Exported something to DB table"
}
});
}


my_array looks like a csv string with multiple lines, e.g.:


["header1, header2, header3", "some_value, 45.99, text"]


I just can't figure out how to simply use this array in my python script(send_array.py)

For now, the script works fine with some data defined locally (cf. second cursor.execute command):

import psycopg2
import psycopg2.extras
import cgitb

def main():
cgitb.enable()

conn_string = "host='...' dbname='...' user='...' password='...' port=..."
conn = psycopg2.connect(conn_string)
cursor = conn.cursor()

cursor.execute("DROP TABLE IF EXISTS myDb.myTable; CREATE TABLE myDb.myTable(id serial PRIMARY KEY, header1 varchar, header2 decimal, header3 varchar);")
cursor.execute("INSERT INTO myDb.myTable (header1, header2, header3) VALUES (%s, %s, %s)", ("local_test1",0.12345,"local_test2"))

# Make the changes to the database persistent
conn.commit()

cursor.close()
conn.close()

if __name__ == "__main__":
main()


So my question is basically:

How would I access the data sent from the Ajax POST, i.e. the my_array array, to be used in the SQL query instead of the locally defined data?

Thanks for any help, I'm still quite new to this and am having trouble finding the answer online.

Answer Source

I finally found a way to get the data from the Ajax command within the Python script. First, I had to stringify the data sent by the browser:

data: JSON.stringify(myArray),

Then, I used sys.stdin in the following command in the python script to store the sent data in a local variable:

myDataInPython = json.load(sys.stdin)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download