Database Table
CREATE TABLE `post` (
`id` int(11) NOT NULL,
`title` varchar(100) NOT NULL,
`content` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `post`
ADD PRIMARY KEY (`id`);
ALTER TABLE `post`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds.
1000 ms = 1 second.
In this tutorial set an interval of 5 seconds
#app.py
from flask import Flask, request, jsonify, render_template
from flaskext.mysql import MySQL #pip install flask-mysql
import pymysql
app = Flask(__name__)
mysql = MySQL()
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = ''
app.config['MYSQL_DATABASE_DB'] = 'testingdb'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)
@app.route('/')
def home():
return render_template('index.html')
@app.route('/autosave', methods=['POST'])
def autosave():
try:
conn = mysql.connect()
cursor = conn.cursor(pymysql.cursors.DictCursor)
if request.method == 'POST':
postid = request.form['postid']
title = request.form['title']
content = request.form['content']
cursor.execute("SELECT count(*) as cntpost FROM post WHERE id=%s", postid)
row = cursor.fetchone()
count = row['cntpost']
print(count)
if count == 0:
sql = "INSERT INTO post(title, content) VALUES(%s, %s)"
data = (title, content)
conn = mysql.connect()
cursor = conn.cursor()
cursor.execute(sql, data)
postid = cursor.lastrowid
print(postid)
conn.commit()
else:
sql = "UPDATE post SET title=%s, content=%s WHERE id=%s"
data = (title, content, postid)
conn = mysql.connect()
cursor = conn.cursor()
cursor.execute(sql, data)
conn.commit()
resp = jsonify(postid)
resp.status_code = 200
return resp
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
if __name__ == "__main__":
app.run()
templates/index.html
//templates/index.html
<html>
<head>
<title>Python Flask Autosave data after specific time with jQuery AJAX and Mysql database</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<p><h1 align="center">Python Flask Autosave data after specific time with jQuery AJAX and Mysql database</h1></p>
<div class="container">
<div class="row">
<b>Title :</b> <input type='text' id='postTitle' class="form-control" placeholder='Enter post title'><br><br>
<b>Content :</b> <textarea id='postContent' class="form-control" placeholder='Enter content' rows="5"></textarea><br><br>
<input type='button' class="btn btn-default" id='submit' value='Submit'>
<input type='hidden' id='postid' value='0' >
</div>
</div>
<script>
//setTimeout(function(){ alert("Hello"); }, 3000); //Display an alert box after 3 seconds (3000 milliseconds):
$(document).ready(function(){
var timer;
var timeout = 5000; // Timout duration 1000 ms = 1 second.
$('#postTitle,#postContent').keyup(function(){
if(timer) {
clearTimeout(timer);
}
timer = setTimeout(saveData, timeout);
});
$('#submit').click(function(){
saveData();
});
});
// Save data
function saveData(){
var postid = $('#postid').val();
var title = $('#postTitle').val().trim();
var content = $('#postContent').val().trim();
if(title != '' || content != ''){
// AJAX request
$.ajax({
url: '/autosave',
type: 'post',
data: {postid:postid,title:title,content:content},
success: function(response){
$('#postid').val(response);
alert('Save Success');
}
});
}
}
</script>
</body>
</html>
