Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get post data from ajax post request in python file

I'm trying to post some data with an ajax post request and execute a python file, retrieving the data in the python file, and return a result.

I have the following ajax code

        $(function () {
                    $("#upload").on("click", function (e) {
                        $.ajax({
                            type: 'post',
                            url: "test1.py",
                            data: {'param1':'abc'},
                            async: false,
                            success: function (response) {
                                console.log(response);
                            }
                        }).done(function (data) {
                            console.log(data);
                        });
                    });
                });

And the following python file

    #! /usr/bin/python
    from __future__ import print_function
    import cgi, cgitb
    def index():
        data = cgi.FieldStorage()
        mydata = data['param1'].value
        return return "test"

I'm getting a keyerror on param1 -> "KeyError: 'param1'". I've also tried to use getValue(data['param1']. It looks like a problem with transferring the data from the ajax call to the python file i want to execute... But i can't figure out why.

Thanks in advance

like image 798
Peter Avatar asked Nov 20 '14 18:11

Peter


Video Answer


1 Answers

I've managed to come up with an solution. I hope other people can get use of it as well.

By the following python code i've manged to get the postdata from the ajax call.

    def index(req):
        postData = req.form
        json = str(postData['param'].value)
like image 64
Peter Avatar answered Oct 27 '22 00:10

Peter