--
-- Table structure for table `checkbox`
--
CREATE TABLE `checkbox` (
`id` int(11) NOT NULL,
`name` varchar(155) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
#app.py
from flask import Flask, render_template, jsonify, request
from flask_mysqldb import MySQL,MySQLdb #pip install flask-mysqldb https://github.com/alexferl/flask-mysqldb
app = Flask(__name__)
app.secret_key = "caircocoders-ednalan"
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'testingdb'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
mysql = MySQL(app)
@app.route('/')
def main():
return render_template('index.html')
@app.route("/insert",methods=["POST","GET"])
def insert():
cursor = mysql.connection.cursor()
cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
if request.method == 'POST':
insert = request.form['checkboxvalue']
cur.execute("INSERT INTO checkbox (name) VALUES (%s)",[insert])
mysql.connection.commit()
cur.close()
msg = 'Data Inserted Successfully!'
else:
msg = 'Invalid'
return jsonify(msg)
if __name__ == '__main__':
app.run(debug=True)
templates/index.html
//templates/index.html
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert Checkbox values in Database using Python Flask Jquery Ajax and MySQLdb</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<h3>Insert Checkbox values in Database using Python Flask Jquery Ajax and MySQLdb</h3>
<label><input type="checkbox" class="get_value" value="Python"> Python</label>
<br/>
<label> <input type="checkbox" class="get_value" value="JavaScript"> JavaScript</label>
<br/>
<label><input type="checkbox" class="get_value" value="Java"> Java</label>
<br/>
<label><input type="checkbox" class="get_value" value="PHP"> PHP</label>
<br/>
<label><input type="checkbox" class="get_value" value="C#"> C#</label>
<br/>
<br/>
<button type="button" name="submit" id="submit">Save</button>
<br/>
<h4 id="result"></h4>
<script>
$(document).ready(function() {
$('#submit').click(function() {
var insert = [];
$('.get_value').each(function() {
if ($(this).is(":checked")) {
insert.push($(this).val());
}
});
insert = insert.toString();
var insert_string = 'checkboxvalue='+insert;
$.ajax({
method: "POST",
url: "/insert",
data: insert_string,
cache: false,
success: function(data){
$("#result").html(data);
}
});
});
});
</script>
</body>
</html>
