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>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8">
<title>Python-jQuery Example</title>
<script src="http://code.jquery.com/jquery-2.0.3.js"></script>
<script>
$(function()
{
$.ajax({
url: "http://localhost/cgi-bin/post.py",
type: "post",
datatype: "html",
data: "here is data",
success: function(response){
$("#div").html(response);
console.log("There is a response");
}
});
});
</script>
</head>
<body>
<div id="div">Default Stuff</div>
</body>
My Python Code:
#!/usr/bin/python
import cgi, cgitb
cgitb.enable()
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?
I figured out that the data needs to be formatted as key-value pairs, like so:
$.ajax({
url: "http://localhost/cgi-bin/variousTests/post.py",
type: "POST",
data: {foo: 'bar', bar: 'foo'},
success: function(response){
$("#div").html(response);
}
});
In the Python script, I used this code to get the data from the POST request (it works the exact same way if a GET request is used):
#!/usr/bin/python
import cgi, cgitb
cgitb.enable() # for troubleshooting
#the cgi library gets vars from html
data = cgi.FieldStorage()
#this is the actual output
print "Content-Type: text/html\n"
print "The foo data is: " + data["foo"].value
print "<br />"
print "The bar data is: " + data["bar"].value
print "<br />"
print data
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With