--
-- Table structure for table `checkbox`
--
CREATE TABLE `checkbox` (
`id` int(11) NOT NULL,
`name` varchar(155) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | #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 ) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | //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> </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> |