I'm using AJAX to send a user-input form to Flask, where it is processed, used in a query, and the results are sent back as a JSON object. AJAX is called upon form submission, and I'm returning the proper query results. But, when the results are returned, the JSON object is printing to the browser window, not maintaining the template format of the original page.
views.py
@app.route('/table_data', methods=['POST'])
def table_data():
request_info = request.form
#Incoming data is processed here and converted into following format:
data = [{'name': 'bill', 'state': 'CA', 'id': 012345},
{'name': 'cindy', 'state': 'NY', 'id': 098765}, ...]
return jsonify(data)
index.html:
<script type="text/javascript" src="{{ url_for('static'), filename='/js/script.js'}}"></script>
<form action="{{ url_for('table_data') }}" class="form-inline" method="post"
role="form" enctype="application/json">
<input type="text" class="form-control" id="name" name="name">
<input type="text" class="form-control" id="state" name="state">
<input type="text" class="form-control" id="id" name="id">
<button type='submit' class="btn btn-default">Submit</button>
</form>
<p id="response"></p>
script.js:
$(document).ready(function() {
$('form').on('submit', function(event) {
$.ajax({
url: '/table_data',
data: $('form').serializeArray(),
type: 'POST',
success: function(response) {
$('#response').text(response);
}
})
});
});
I expect the returned JSON object to be printed to the screen underneath the form, but instead, the data returned is printed directly to the browser window, which doesn't maintain the structure of 'index.html' (which has navbars and a form). I am returned this:
[
{
'name': 'bill',
'state': 'CA',
'id': 012345
},
{
'name': 'cindy',
'state': 'NY',
'id': 098765
},
...
]
Again, this is the proper format, but the data isn't printing to the data
like I want it to. Brand new to JavaScript and jQuery/AJAX, so I'm fairly sure I'm missing something pretty trivial.