Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AJAX Posting to Python cgi [duplicate]

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);
like image 739
TheMonkeyMan Avatar asked May 23 '12 13:05

TheMonkeyMan


1 Answers

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
}
like image 190
sente Avatar answered Nov 15 '22 18:11

sente