Anithra Ranasinghe Anithra Ranasinghe - 4 months ago 29
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

getSchedule.py
. the db connection is in a separate file
webairdb.py


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

getSchedule.py



#!D:/Programming/Software/python3.4.4/python
import sys, json,cgi, cgitb, mysql.connector, webairdb

cgitb.enable()
fs = cgi.FieldStorage()

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

sys.stdout.write("\n")
sys.stdout.write("\n")

conn = webairdb.getConnection()
conn.close()

listr = [11111]

sys.stdout.write(json.dumps(listr))
sys.stdout.write("\n")

sys.stdout.close()


webairdb.py



#!D:/Programming/Software/python3.4.4/python
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():
print("aaaqqqq")
return conn

Answer

In webairdb.py 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.