article

Monday, July 12, 2021

Progress Bar Data Insert using Python Flask Jquery Ajax Bootstrap and PostgreSQL database

Progress Bar Data Insert using Python Flask Jquery Ajax Bootstrap 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 tbl_user (
id serial PRIMARY KEY,
username VARCHAR ( 150 ) NOT NULL,
useremail 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 index():
    return render_template('index.html')
  
@app.route("/ajaxprogressbar",methods=["POST","GET"])
def ajaxprogressbar():
    if request.method == 'POST':
        username = request.form['username']
        useremail = request.form['useremail']
        print(username)
        cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
        cur.execute("INSERT INTO tbl_user (username, useremail) VALUES (%s, %s)",[username, useremail])
        conn.commit()
        cur.close()
        msg = 'New record created successfully'    
    return jsonify(msg)
    
if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html>
<head>
<title>Progress Bar Data Insert using Python Flask Jquery Ajax Bootstrap and PostgreSQL database</title>  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
$(document).ready(function(){
    $('#sample_form').on('submit', function(event){
        event.preventDefault();
        var count_error = 0;
        if($('#username').val() == '') {
            $('#first_name_error').text('User Name is required');
            count_error++;
        }else
        {
            $('#first_name_error').text('');
        }
  
        if($('#useremail').val() == '') {
            $('#last_name_error').text('Email is required');
            count_error++;
        }else {
            $('#last_name_error').text('');
        }
  
        if(count_error == 0)
        {
            $.ajax({
                url:"/ajaxprogressbar",
                method:"POST",
                data:$(this).serialize(),
                beforeSend:function()
                {
                    $('#save').attr('disabled', 'disabled');
                    $('#process').css('display', 'block');
                },
                success:function(data)
                { 
                    var percentage = 0;
                    var timer = setInterval(function(){
                    percentage = percentage + 20;
                    progress_bar_process(percentage, timer,data);
                    }, 1000);
                }
            })
        }else{
            return false;
        }
  });
    
  function progress_bar_process(percentage, timer,data)
  {
    $('.progress-bar').css('width', percentage + '%');
    if(percentage > 100)
    {
        clearInterval(timer);
        $('#sample_form')[0].reset();
        $('#process').css('display', 'none');
        $('.progress-bar').css('width', '0%');
        $('#save').attr('disabled', false);
        $('#success_message').html(data);
        setTimeout(function(){
        $('#success_message').html('');
        }, 5000);
    }
  }
    
 });
</script>
</head>
<body><br /><br />
<div class="container">
   <h1 align="center">Progress Bar Data Insert using Python Flask Jquery Ajax Bootstrap and PostgreSQL database</h1>
   <br />
   <div class="panel panel-default">
        <div class="panel-heading">
        <h3 class="panel-title">Registration</h3>
        </div>
        <div class="panel-body">
            <span id="success_message"></span>
            <form method="post" id="sample_form">
                <div class="form-group">
                    <label>User Name</label>
                    <input type="text" name="username" id="username" class="form-control" />
                    <span id="first_name_error" class="text-danger"></span>
                </div>
                <div class="form-group">
                    <label>Email</label>
                    <input type="text" name="useremail" id="useremail" class="form-control" />
                    <span id="last_name_error" class="text-danger"></span>
                </div>
                <div class="form-group" align="center">
                    <input type="submit" name="save" id="save" class="btn btn-info" value="Save" />
                </div>
            </form>
            <div class="form-group" id="process" style="display:none;">
                <div class="progress">
                    <div class="progress-bar progress-bar-striped active bg-success" role="progressbar" aria-valuemin="0" aria-valuemax="100" style=""></div>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>

Related Post