goldage5 goldage5 - 3 years ago 557
Python Question

POST data to Python CGI script via jQuery AJAX

I'm trying to setup a simple script where some data is sent using the jQuery .ajax function to a Python CGI script. The Python script would just make the data posted to it uppercase, and then return that data to the HTML file, where a div would be updated with the content.

I have the code shown below. When I run it, the AJAX call executes, but the div is not updated with the content. the div is not updated with the data being sent.

How would I modify this code so that it updates with the data being sent?

I appreciate any help at all.

My HTML Code:

<!DOCTYPE html>
<meta http-equiv="content-type" content="text/html;charset=UTF-8">
<title>Python-jQuery Example</title>
<script src=""></script>
url: "http://localhost/cgi-bin/",
type: "post",
datatype: "html",
data: "here is data",
success: function(response){
console.log("There is a response");

<div id="div">Default Stuff</div>

My Python Code:


import cgi, cgitb

data = cgi.FieldStorage()

print "Content-Type: text/html"
print data

EDIT: I have updated my code to what is currently shown, and now the document updates with this string:

FieldStorage(None, None, [])

How would I modify my code so that the div updates with the data being sent?

Answer Source

I believe that the "data" inside the $.ajax should be like a hash of a key-value pairs. try:

  data: {
    a: "aa",
    b: "bb"

If you see in the div something like:

MiniFieldStorage('a', 'aa')

Then you should access it via:

my_param = cgi.getfirst('a')

print "Content-Type: text/html\n"
print my_param

If it's still not working, can you test it via GET instead of POST ? In addition, what's the structure of the AJAX file(s) that you're accessing ? ( is the file inside a sub-directory ? etc... )

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download