7

Possible Duplicate:
Post JSON to Python CGI

I have got Apache2 Installed and Python working.

I am having a problem though. I have two pages.

One a Python Page and the other an Html Page with JQuery I couldent pase the Src to the google jquery link.

Can someone please tell me how I can get my ajax post to work correctly.

    $(function()
    {
        alert('Im going to start processing');

        $.ajax({
            url: "saveList.py",
            type: "post",
            data: {'param':{"hello":"world"}},
            dataType: "application/json",
            success : function(response)
            {
                alert(response);
            }
        });
    });

And the Python Code

import sys
import json

def index(req):
    result = {'success':'true','message':'The Command Completed Successfully'};

    data = sys.stdin.read();

    myjson = json.loads(data);

    return str(myjson);
Community
  • 1
  • 1
TheMonkeyMan
  • 8,622
  • 8
  • 27
  • 42

1 Answers1

20

Here's an example html file and accompanying python CGI script which should get you going:

Using this html:

<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8">

        <title>test</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
        <script>

            $(function()
            {
                $('#clickme').click(function(){
                    alert('Im going to start processing');

                    $.ajax({
                        url: "/scripts/ajaxpost.py",
                        type: "post",
                        datatype:"json",
                        data: {'key':'value','key2':'value2'},
                        success: function(response){
                            alert(response.message);
                            alert(response.keys);
                        }
                    });
                });
            });

        </script>
    </head>
    <body>
        <button id="clickme"> click me </button>
    </body>

</html>

and this script:

#!/usr/bin/env python

import sys
import json
import cgi

fs = cgi.FieldStorage()

sys.stdout.write("Content-Type: application/json")

sys.stdout.write("\n")
sys.stdout.write("\n")


result = {}
result['success'] = True
result['message'] = "The command Completed Successfully"
result['keys'] = ",".join(fs.keys())

d = {}
for k in fs.keys():
    d[k] = fs.getvalue(k)

result['data'] = d

sys.stdout.write(json.dumps(result,indent=1))
sys.stdout.write("\n")

sys.stdout.close()

After clicking the button you can see the cgi script returns:

{
 "keys": "key2,key", 
 "message": "The command Completed Successfully", 
 "data": {
  "key2": "value2", 
  "key": "value"
 }, 
 "success": true
}
sente
  • 2,327
  • 2
  • 18
  • 24
  • I get undefined instead of what it's supposed to return – erdomester Jan 30 '16 at 11:00
  • I get "unsupported method ("post")" whether I run it on `localhost` or Google Cloud. – Randoms Jul 26 '17 at 18:23
  • Using this example fs = cgi.FieldStorage() also didn't give me any of the key/value pairs sent by the Ajax 'data' param. Instead of cgi.FieldStorage() I used: fs = sys.stdin.read() which gives a string of format: key=value&key2=value2. From this you can create a python dictionary using d = dict(item.split("=") for item in fs.split("&")) Also, using print() is better than sys.stdout.write() because print() adds a line feed itself. It also automatically converts the parameters to a string. So for the last three lines in the python script above you can just use: print(json.dumps(result,indent=1)) – FlexMcMurphy Feb 02 '20 at 12:53
  • example does not work. – Noel Aug 13 '22 at 21:43