Ajax script with python backend

0
by on June 10, 2013 at 3:07 pm

At my day job, I’m a Linux System Administrator.  This roughly translates to “Everything System Administrator” as I work in a lot of other capacities as well.  One of my duties is maintaining an internal web portal that runs on a RHEL 6 system.  A good portion of our portal runs on Python and Perl CGI scripts.  I wanted to dynamically update part of a page and I needed to make an Ajax call to a Python script instead of a normal PHP or ASP (etc).  I ran into a problem with a not so obvious solution compared to how people make calls to PHP backends.

The script below outlines how to get just the desired <body> portion of the data returned by the Python backend, and trims leading and trailing spaces that might interfere with the operation of your program.  This script is for creating a toggle button ( on / off ) which calls a function in the Python backend.  Because our backend  is a CGI script written in python, python has to print header information, which would be returned to our Ajax script above if we don’t select “document.body” for the context.

FYI, I am using jquery 1.10.1 if you can’t already tell ;)


$(document).ready(function(){

function setoff(myid) {
 $.ajax({
 type: 'POST',
 url: "/cgi-bin/backend.py",
 data: {mymode: "setoff", myitem: myid},
 dataType: 'html',
 context: document.body,
 global: false,
 async:false,
 success: function(data) {
 mylist = $(data).text().trim();
 return mylist;
 }
 });
}

function seton(myid) {
 $.ajax({
 type: 'POST',
 url: "/cgi-bin/backend.py",
 data: {mymode: "seton", myitem: myid},
 dataType: 'html',
 context: document.body,
 global: false,
 async:false,
 success: function(data) {
 mylist = $(data).text().trim();
 return mylist;
 }
 });
}
$(document).on('click', '.istoggled', function() {
 setoff(this.id);
 $(this).toggleClass("istoggled nottoggled");
});
$(document).on('click', '.nottoggled', function() {
 seton(this.id);
 $(this).toggleClass("istoggled nottoggled");
});

});

Here’s a quick example of a Python backend script.


#!/usr/bin/python
import cgi

print """Content-type: text/html; charset=utf-8\n\n
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>"""

form = cgi.FieldStorage()
mymode = form.getvalue("mymode", "error")
myitem = form.getvalue("myitem", "error")
def doseton(myitem):
### Code here for backend operation
 print myitem
def dosetoff(myitem):
### Code here for backend operation
 print myitem

&nbsp;

if myitem != "error":
 if mymode == "seton":
 doseton(myitem)

elif mymode == "setoff":
 dosetoff(myitem)

else:
 print "error"
else:
 print "error"

print """</html>"""

Obviously, this file is abbreviated because chances are what I’m doing on the back end isn’t the same as what you’ll want to do ;)

in How-To

, , , , ,

You can skip to the end and leave a response. Pinging is currently not allowed.

Categories