Skip to content

Instantly share code, notes, and snippets.

@jennielees
Last active November 8, 2017 20:28
Show Gist options
  • Save jennielees/40249db903325640bfaa to your computer and use it in GitHub Desktop.
Save jennielees/40249db903325640bfaa to your computer and use it in GitHub Desktop.
flask jquery jsonify and ajax, sitting in a tree
Server:
from flask import request, jsonify
from models import Result
@route("/update_search")
def update_search():
q = request.args.get('q')
results = Result.query.filter_by(name=q)
root = { 'result': results.all() }
return jsonify(root)
--
Web:
<input type='text' id='text_input' value=''>
<button type='submit' value='Submit' id='submit'>
<div id='results'></div>
<script src="/static/js/jquery.min.js"></script>
<script type="text/javascript">
function update_search(q) {
$.ajax({ url:'/update_search?q=' + q }) // Call the URL update_search with q as the 'q' parameter
.done(function(data) { // When done, this runs on the result
$.each(data.result, function(index, result) { // Our 'data' variable is an array, so for each item (call it 'result'):
var row = '<div>' + result.name + '</div><div>' + result.location + '</div>'; // generate a DIV
$('#results').append(row).fadeIn('slow'); // and add it as a child to the div with ID 'results', using jQuery chaining to animate
});
});
};
// When the document has finished loading:
$(document).ready(function(){
$('#submit').click( function() { // When the div with ID 'submit' is clicked
update_search($('#text_input').val()); // call update_search with the contents of text_input
});
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment