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.
I expect the returned JSON object to be printed to the screen in the p tag with id="result", but instead, the data returned is printed directly to the browser window,
AJAX Script
<script type=text/javascript>
$(function() {
$('button#submit').bind('click', function() {
$.getJSON('/index', {
text: $('textarea[name="text"]').val(),
},
sucess: function(data) {
$('#result').text(JSON.stringify(data.result));
});
return false;
});
});
HTML
<div class="col ">
<form action="/" method="POST">
<div class="form-group shadow p-3 bg-white rounded">
<!-- <label for="content">Content</label> -->
<textarea class="form-control bg-light" id="text" name="text"
placeholder="Copy and paste the text of the URL of the article"
rows="13"
style="resize: none"></textarea>
<a href="#" id="submit">
<button class="btn btn-danger text-white mt-2" type="submit">Summarize
</button>
</a>
</div>
</form>
</div>
<div class="col">
<div class="col shadow p-3 h-100 bg-white rounded">
<p id="result"></p>
</div>
</div>
FLASK APP
@app.route("/", methods=["GET", "POST"])
def index():
if request.method == "POST":
text = request.form.get("text")
if text:
return jsonify(result=text)
else:
return jsonify(result="input needed")
return render_template("index.html")