I am trying to implement a form containing a list of cities, using a JSON array and an autocomplete function.
My ajax call is successful and gives the expected success alert, but I'm still not getting the JSON array data.
The problem is that my suggest_json_application function is failing at the 'if form.has_key('term')' statement and giving the message "form has no key".
How can I pass the form data to the function properly through the ajax call, with the key term
?
HTML form
</head>
<body>
<form>
<fieldset><legend>Cities</legend>
<input type='text' name='term' id='term'>
</form>
JQuery
$('document').ready(function() {
var term = $('#term').val();
$.ajax({
url: "/suggestjson",
type: "POST",
dataType: "json",
data: JSON.stringify({'term': term}),
success: function (data) {
alert('success');
console.log( data );
}
});
});
Webserver
cities = ['New York', 'London', 'Los Angeles',
'Paris', 'San Francisco', 'Adelaide']
if environ['PATH_INFO'] == "/suggestjson":
return suggest_json_application(environ, start_response)
def suggest_json_application(environ, start_response):
//Return JSON array of completions for a city name
form = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ)
if form.has_key('term'):
print "form has key"
q = form.getvalue("term", "")
matches = [c for c in cities if c.lower().startswith(q.lower())]
else:
print "form has no key"
matches = []
return json.dumps(matches)