index.html
<div class="div-inputs">
<input type="text" id="input" placeholder="Enter expression" value="1+2"/>
<input type="submit" id="btn" value="Execute"/>
</div>
<input type="text" id="output" readonly="readonly">
<script src="{{url_for('static', filename='js/jquery-3.2.1.min.js')}}"></script>
<script type="text/javascript">
document.querySelector('#btn').addEventListener('click', (e) => {
let equation = document.querySelector('#input').value;
$.ajax({
url: "/",
type: "POST",
data: equation,
success: function(){
console.log("successfull POST");
let result = {{evaluate}}
document.querySelector('#output').value = result;
}
});
});
</script>
main.py
from flask import Flask
from flask import url_for, jsonify, render_template, request, json
from math import *
app=Flask(__name__)
@app.route('/', methods=["GET","POST"])
def index() :
evaluate = ""
if request.method == 'POST':
toEvalFromJS = request.get_json()
evaluate = eval(str(toEvalFromJS))
return render_template('index.html', evaluate=evaluate)
return render_template('index.html')
if __name__ == "__main__":
app.run(port=10, debug=True)
error
(index):26 successfull POST
(index):28 Uncaught ReferenceError: Cannot access 'result' before initialization
at Object.success ((index):28:53)
at i (jquery-3.2.1.min.js:2:28017)
at Object.fireWith [as resolveWith] (jquery-3.2.1.min.js:2:28783)
at A (jquery-3.2.1.min.js:4:14035)
at XMLHttpRequest.<anonymous> (jquery-3.2.1.min.js:4:16323)
I know what the error means but I could only get such far.
I have already read the following questions:
- jquery - return value using ajax result on success
- How to return the response from an asynchronous call
but they did not help me solve my problem.
What I want to do: User input an expression string, then click on the submit button and get the evaluated string back.
How could I get the evaluated string?
I am new to flask, I do it just for practice