0

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.

2
  • Possible duplicate of Get post data from ajax post request in python file Commented Feb 26, 2017 at 11:49
  • Thanks for posting, however I wanted another solution which didn't rely on FieldStorage() or form, and found a more direct answer to my question of how to get a hold of the data being sent, see my answer below. Commented Mar 1, 2017 at 9:52

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.