article

Thursday, July 22, 2021

Insert Checkbox values using Python Flask Jquery Ajax and PostgreSQL Database

Insert Checkbox values using Python Flask Jquery Ajax and PostgreSQL Database

install psycopg2 https://pypi.org/project/psycopg2/
Psycopg is the most popular PostgreSQL database adapter for the Python programming language.
(venv) PS C:\flaskmyproject> pip install psycopg2

CREATE TABLE checkbox (
id serial PRIMARY KEY,
name VARCHAR ( 150 ) NOT NULL
);
app.py
#app.py
from flask import Flask, render_template, jsonify, request
import psycopg2 #pip install psycopg2 
import psycopg2.extras
      
app = Flask(__name__)
      
app.secret_key = "caircocoders-ednalan"
      
DB_HOST = "localhost"
DB_NAME = "sampledb"
DB_USER = "postgres"
DB_PASS = "admin"
          
conn = psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST)

@app.route('/')
def main():
    return render_template('index.html')
 
@app.route("/insert",methods=["POST","GET"])
def insert():  
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    if request.method == 'POST':
        insert = request.form['checkboxvalue'] 
        cur.execute("INSERT INTO checkbox (name) VALUES (%s)",[insert])
        conn.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 using Python Flask Jquery Ajax and PostgreSQL Database</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
    <h3>Insert Checkbox values using Python Flask Jquery Ajax and PostgreSQL Database</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="Swift"> Swift</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>

Related Post