I have created a JS that creates 2 user input fields when a button is clicked that will then show on the html page. I want the 2 inputs to be passed once they are created into the flask application. I have everything in order but nothing seems to work.
Should I reference the input fields another way? I am very stuck and some guidance would be much appreciated.
Please find my code below
main.py
import sys
from flask import request, render_template, Flask, session, redirect, url_for
app = Flask(__name__)
app.config['SECRET_KEY'] = 'hjshjhdjah kjshkjdhjs'
@app.route('/', methods=['GET', 'POST'])
def inputNum():
if request.method == 'POST':
num1 = request.form.get("num0")
session["num1"] = num1
num2 = request.form.get("num1")
session["num2"] = num2
print(session["num1"])
return redirect(url_for("results"))
return render_template("inputNum.html")
@app.route('/results')
def results():
if "num1" and "num2" in session:
num1 = session["num1"]
num2 = session["num2"]
old_stdout = sys.stdout
log_file = open("message.log", "w")
sys.stdout = log_file
addNum(num1, num2)
sys.stdout = old_stdout
log_file.close()
with open("message.log", "r") as f:
content = f.read()
return app.response_class(content, mimetype='text/plain')
else:
return redirect(url_for('inputNum'))
def addNum(num1, num2):
num1 = int(num1)
num2 = int(num2)
sum = num1 + num2
print(sum)
if __name__ == '__main__':
app.run(debug=True)
inputFields.js
var num = 2; // ads 2 fields at a time
var createInputs = function () {
$("#ip_div").append('<form id="form"></form>');
for (var i = 0; i < num; i++) {
$("#form").append("<input></input>");
}
};
$("#btn").click(function () {
createInputs();
//create unique ID for each input
$("#form")
.find("input")
.each(function (i) {
$(this).attr("type", "number");
$(this).attr("name", "num" + i);
$(this).attr("id", "num" + i);
$(this).attr("placeholder", "number" + i);
});
});
inputNum.html
<button id="btn"> Add new fields </button>
<div id="ip_div"> <form action="{{ url_for("inputNum")}}" method="post">
</div>
<br>
<button type="submit">Submit for addition </button>
<script type=text/javascript src="{{ url_for('static', filename='jquery.js') }}"></script>
<script type=text/javascript src="{{ url_for('static', filename='inputFields.js') }}"></script>
</form>
results.html
<!DOCTYPE html>
<title xmlns="http://www.w3.org/1999/html">
<head>
<meta http-equiv="refresh" content="10">
<title>Results</title>
</head>
<body>
<h1>Log file ...</h1>
<script>
// function for adjusting iframe height to log size
function resizeIframe(obj) {
obj.style.height = obj.contentWindow.document.documentElement.scrollHeight + 'px';
}
</script>
<iframe src="{{ url_for('results') }}" frameborder="0" style="overflow:hidden;width:100%" width="100%" frameborder="0" scrolling="no" onload="resizeIframe(this)"></iframe>
</body>
</html>
