I am using Flask to develop a webpage. Once the form is posted, it is displayed and on a click of a button, the value displayed is incremented. I want to insert this incremented value to the database. I have used javascript and ajax to update the page. But not sure how to use this output from javascript to Flask and then insert to DB. Please help! Here is my code.
**HTML1:**
<!doctype html>
<html>
<head>
<title>Hi</title>
<body>
<h3><strong>Enter the details</strong></h3>
<form action = "/update" method = "POST">
<p>ID <input type ="number" name = "ID" required/></p>
<a><input type="submit" value="Store" /></a>
</form>
</body>
</html>
HTML2
<html>
<body>
<h1><strong>Output</strong></h1>
<div id="demo">
<a>ID</a>
<p id="number2">{{mydata}}</p>
</div>
<div id="btn">
<button id="click" type="button" onclick="pqr()">Change Content</button>
</div>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
function pqr(){
var no1= document.getElementById("number2").innerHTML;
document.getElementById("number2").setAttribute("no1", no1 );
var abc=document.getElementById("number2").getAttribute("no1");
var no2= Number(abc)+ 1;
document.getElementById("number2").innerHTML = no2;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
}
xhttp.open("POST", "/update", true);
xhttp.send();
};
}
</script>
</body>
</html>
**Flask:**
app.config['MYSQL_HOST'] = '****'
app.config['MYSQL_USER'] = '***'
app.config['MYSQL_PASSWORD'] = '********'
app.config['MYSQL_DB'] = '****'
@app.route ('/', methods = ['POST', 'GET'])
def login():
return render_template('page3.html')
@app.route ('/update', methods = ['POST', 'GET'])
def update():
if request.method == 'POST':
userDetails=request.form
mydata = userDetails['ID']
cur = mysql.connection.cursor()
cur.execute("INSERT INTO mytable(id,uq_id) VALUES(%s,%s)", (mydata))
mysql.connection.commit()
cur.close()
return render_template('page4.html', mydata=mydata)
I am able to dynamically update the page. Just want to know how to update the database from javascript
question from:
https://stackoverflow.com/questions/66057589/insert-data-into-mysql-database-through-javascript-and-flask 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…