Reputation: 15
I've been trying to use my script that I previously written to turn Arabic numerals to Roman. User inputs numbers and my script turns them to Roman ones. Script runs fine, but me trying to embed it to a webpage is not working as intended. I googled solutions to that and everyone tell I need to get the value from a form, which I did:
<form action="toroman" method="POST">
<input type="number" name="arabic" onChange="toroman(this.value)" oninput="toroman(this.value)">
<p>{{ romanfinal }}</p>
</form>
And this is my server.py that should be printing out the number of the same page, but it doesn't do that, instead when I press "Enter" when submitting the value it creates a new page and displays correct answer.
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route("/")
def index():
return render_template("index.html")
@app.route("/toroman", methods=['POST'])
def toroman():
arabic = request.form['arabic']
# some unnecessarily numerous lines of code that basically turn Arabic-system number to Roman system
return romanfinal
if __name__ == "__main__":
app.run(debug=True)
This is like the only time it actually worked, when I try to change it so something else, it just gives me errors. Please tell me what exactly I don't understand about it.
Upvotes: 1
Views: 1519
Reputation: 2379
FLASK
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
@app.route("/")
def index():
return render_template("index.html")
@app.route("/toroman", methods=['POST'])
def toroman():
arabic = request.data['arabic']
#pass arabic into your translation function
translation = translate()
#return JSON response to AJAX
return jsonify(translation = translation)
if __name__ == "__main__":
app.run(debug=True)
JS
$(document).ready(function(){
document.getElementById('toroman_form').addEventListener('keyup', function() {
$.ajax({
type: 'POST',
url: '/toroman', //flask route to which data is sent
data: $('#arabic').val(), // input field value
contentType:'application/json; charset=utf-8',
dataType: "json",
success: function(data) {
translation = data.translation //response received from flask
$('#translated').text(translation) //display translation in html <p> tag
},
error: function() {
alert("Transaction Failed");
}
});
});
}
HTML
<form id="toroman_form">
<input type="number" id="arabic">
<p id="translated"><!--translation is dislayed here--></p>
</form>
Upvotes: 0
Reputation: 1173
Your toroman():
function should return index.html with the parameter :
@app.route("/toroman", methods=['POST'])
def toroman():
arabic = request.form['arabic']
# some unnecessarily numerous lines of code that basically turn Arabic-system number to Roman system
return render_template("index.html", data = romanfinal)
Then you can use the value data
in your HTML top level like that : {{data}}
Upvotes: 1