Anithra Ranasinghe Anithra Ranasinghe - 7 months ago 47
Ajax Question

Using JSON with AJAX and Python database

I am new to python and am trying to access the db though python and return some results in a JSON array using AJAX.

I test it by returning a JSON list and alerting it using js. it works when I don't use the db connection but as soon as I add it the js alert stops too. the db connection seems to work properly when I run the file
. the db connection is in a separate file

Can someone please try to help me figure out whats wrong?

import sys, json,cgi, cgitb, mysql.connector, webairdb

fs = cgi.FieldStorage()

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


conn = webairdb.getConnection()

listr = [11111]



import cgi, cgitb, imp, mysql.connector

host ="localhost"
db = "webair"
user = "root"
password = ""

def getConnection():
conn = mysql.connector.connect(user=user,password=password,host=host,database=db)
if conn.is_connected():
return conn


In you write to sys.stdout (that is what print does) - putting effectively breaking the json output. (You might want to have a look at the output by pressing F12 in your browser)

So just remove it and either write to sys.stderr or use logging instead.

You should also consider using wsgi instead of cgi which makes things a bit easier (no need to care about printing at all) or a framework like bottle or cherrypy.