article

Showing posts with label PostgreSQL. Show all posts
Showing posts with label PostgreSQL. Show all posts

Monday, July 5, 2021

Table Edit using jquery ajax Python Flask and PostgreSQL Database

Table Edit using jquery ajax Python Flask 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 programming (
id serial PRIMARY KEY,
title VARCHAR ( 150 ) NOT NULL
);

INSERT INTO
    programming(title)
VALUES
('Python Flask'),
('Python Django'),
('Express.js'),
('Laravel'),
('Spring'),
('Angular'),
('React'),
('Vue');
app.py
#app.py
from flask import Flask, render_template, request, jsonify
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():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    cur.execute("SELECT * FROM programming ORDER BY id ASC")
    topphpframework = cur.fetchall() 
    return render_template('index.html', topphpframework=topphpframework)
     
@app.route("/ajax",methods=["POST","GET"])
def ajax():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)    
    if request.method == 'POST':
        getid = request.form['id']
        getname = request.form['name']
        print(getid)
        cur.execute("UPDATE programming SET title = %s WHERE id = %s ", [getname, getid])
        conn.commit()       
        cur.close()
    return jsonify('Record updated successfully')

if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Table Edit using jquery ajax Python Flask and PostgreSQL Database</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
  $(".edit_tr").click(function() {
    var ID=$(this).attr('id');
    $("#first_"+ID).hide();
    $("#first_input_"+ID).show();
  }).change(function(){
      var ID=$(this).attr('id');
      var first=$("#first_input_"+ID).val();
      var dataString = 'id='+ ID +'&name='+first;
      $("#first_"+ID).html('<img src="/staticf/img/loader.gif" />');
      if(first.length>0){
        $.ajax({
          type: "POST",
          url: "/ajax",
          data: dataString,
          cache: false,
          success: function(html)
          {
            $("#first_"+ID).html(first);
          }
        });
      }else{
        alert('Enter something.');
      }
  });
    
  $(".editbox").mouseup(function() {
   return false
  });
  $(document).mouseup(function() {
      $(".editbox").hide();
      $(".text").show();
  });
});
</script>
</head>
<body>
<center><p><h1>Table Edit using jquery ajax Python Flask and PostgreSQL Database</h1></p></center>
<div style="margin:0 auto; width:350px; padding:10px; background-color:#fff;"> 
<table width="100%" border="0">
  <tr class="head">
  <th>Frameworks</th>
  </tr>
  {% for row in topphpframework %}
      <tr id="{{row.id}}" bgcolor="#f2f2f2" class="edit_tr">
        <td width="50%" class="edit_td">
        <span id="first_{{row.id}}" class="text">{{row.title}}</span>
        <input type="text" name="name" value="{{row.title}}" class="editbox" id="first_input_{{row.id}}" />
        </td>
      </tr>
    {% endfor %}
</table>
</div>
<style>
  body
  {
  font-family:Arial, Helvetica, sans-serif;
  font-size:16px;
  }
  .head
  {
  background-color:#333;
  color:#FFFFFF
  }
  .edit_tr:hover
  {
  background:url(/static/img/edit.png) right no-repeat #80C8E5;
  cursor:pointer;
  }
  .editbox
  {
  display:none
  }
  .editbox
  {
  font-size:16px;
  width:270px;
  background-color:#ffffcc;
  border:solid 1px #000;
  padding:4px;
  }
  td
  {
  padding:10px;
  }
  th
  {
  font-weight:bold;
  text-align:left;
  padding:4px;
  }
  </style>
</body>
</html>

Sunday, July 4, 2021

Dynamic Drag and Drop Order List With jQuery Ajax and Python Flask PostgreSQL Database

Dynamic Drag and Drop Order List With jQuery Ajax and Python Flask 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 dragdrop (
id serial PRIMARY KEY,
text VARCHAR ( 150 ) NOT NULL,
listorder INT NOT NULL
);

INSERT INTO
    dragdrop(text,listorder)
VALUES
('Ajax', 3),
('Jquery', 5),
('PHP', 6),
('Mysqli', 7),
('Javascript', 1),
('Java', 4),
('Python', 2);

jqueryui sortable https://jqueryui.com/sortable/
app.py
 
#app.py
from flask import Flask, render_template, request, jsonify
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():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    cur.execute("SELECT * FROM dragdrop ORDER BY listorder ASC")
    dragdrop = cur.fetchall() 
    return render_template('index.html', dragdrop=dragdrop)
 
@app.route("/updateList",methods=["POST","GET"])
def updateList():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    if request.method == 'POST':
        cur.execute("SELECT * FROM dragdrop")    
        number_of_rows = cur.rowcount      
        getorder = request.form['order']    
        print(getorder)
        order = getorder.split(",", number_of_rows)
        print(order)
        count=0   
        for value in order:
            count +=1
            print(count)                       
            cur.execute("UPDATE dragdrop SET listorder = %s WHERE id = %s ", [count, value])
            conn.commit()       
        cur.close()
    return jsonify('Successfully Updated')
 
if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dynamic Drag and Drop Order List With jQuery Ajax and Python Flask PostgreSQL Database</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript">
$(document).ready(function(){  
   function slideout(){
    setTimeout(function(){
      $("#response").slideUp("slow", function () {
    });
    }, 2000);
  }
   
  $("#response").hide();
  $(function() {
    $("#list ul").sortable({ opacity: 0.8, cursor: 'move', update: function() {
      var item_order = new Array();
      $('ul.reorder li').each(function() {
          item_order.push($(this).attr("id"));
      }); 
      var order_string = 'order='+item_order;
      $.ajax({
        method: "POST",
        url: "/updateList",
        data: order_string,
        cache: false,
        success: function(data){    
            $("#response").html(data);
            $("#response").slideDown('slow');
            slideout();
        }
    });               
    }         
    });
   });
  
}); 
</script>
</head>
<body>
<center>  
<p><h1>Dynamic Drag and Drop Order List With jQuery Ajax and Python Flask PostgreSQL Database</h1></p>
<div style="width:300px;">
  <div id="list">
  <div id="response"> </div>
      <ul class="reorder">
        {% for row in dragdrop %}
        <li id="{{row.id}}">{{row.text}}
          <div class="clear"></div>
        </li>
        {% endfor %}
      </ul>
  </div>
</div>
</center>

<style>
ul {
 padding:0px;
 margin: 0px;
}
#response {
 padding:10px;
 background-color:#9F9;
 border:2px solid #396;
 margin-bottom:20px;
}
#list li {
 margin: 0 0 3px;
 padding:8px;text-align:left;
 background-color:#00CCCC;
 color:#fff;
 list-style: none;
 border: #CCCCCC solid 1px;
}
</style>
</body>
</html>

Saturday, July 3, 2021

Date Range Search with Python Flask PostgreSQL jQuery Ajax and DatePicker

Date Range Search with Python Flask PostgreSQL jQuery Ajax and DatePicker

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

Datepicker https://jqueryui.com/datepicker/

CREATE TABLE orders (
id serial PRIMARY KEY,
customer_name VARCHAR ( 150 ) NOT NULL,
purchased_items VARCHAR ( 150 ) NOT NUL,L
purchased_date TIMESTAMP NOT NULL,
price DOUBLE PRECISION
);


INSERT INTO
    orders(customer_name,purchased_items,purchased_date,price)
VALUES
('Airi Satou', 'iPhone', '2020-05-07', 649.00),
('Angelica Ramos', 'Samsung Galaxy', '2020-11-10', 2500.00),
('Ashton Cox', 'Infinix Note 7', '2020-09-10', 299.09),
('Bradley Greer', 'Macbook Pro', '2020-11-26', 1799.50),
('Brenden Wagner', 'Samsung 50\" Smart 4K UHD TV ', '2020-11-27', 479.00),
('Brielle Williamson', '7 Series Curved LED 4K UHD', '2019-11-27', 269.00),
('Bruno Nash', 'iMac', '2019-11-28', 1999.05),
('Caesar Vance', 'Dell Inspiron 3573', '2019-11-30', 1999.05),
('Cara Stevens', 'Tlc 40inch tv Roku tv', '2019-12-07', 649.00),
('Cedric Kelly', 'Acer Aspire 3', '2021-01-13', 199.00);
app.py
 
#app.py
from flask import Flask, render_template, request, jsonify, flash, redirect
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():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    cur.execute("SELECT * FROM orders ORDER BY id desc")
    orders = cur.fetchall() 
    return render_template('index.html', orders=orders)
  
@app.route("/range",methods=["POST","GET"])
def range(): 
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor) 
    if request.method == 'POST':
        From = request.form['From']
        to = request.form['to']
        print(From)
        print(to)
        query = "SELECT * from orders WHERE purchased_date BETWEEN '{}' AND '{}'".format(From,to)
        cur.execute(query)
        ordersrange = cur.fetchall()
    return jsonify({'htmlresponse': render_template('response.html', ordersrange=ordersrange)})

if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Date Range Search with Python Flask PostgreSQL jQuery Ajax and DatePicker</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css"/>
</head>
<body>
<br/>
<div class="container">
    <h2 align="center">Date Range Search with Python Flask PostgreSQL jQuery Ajax and DatePicker</h2>
    <br/>
    <div class="row">
    <div class="col-md-2">
        <input type="text" name="From" id="From" class="form-control" placeholder="From Date"/>
    </div>
    <div class="col-md-2">
        <input type="text" name="to" id="to" class="form-control" placeholder="To Date"/>
    </div>
    <div class="col-md-8">
        <input type="button" name="range" id="range" value="Range" class="btn btn-success"/>
    </div>
    <div class="clearfix"></div>
    <br/>
    </div>
    <div id="purchase_order">
    <table class="table table-bordered">
        <tr>
        <th width="5%">ID</th>
        <th width="35%">Customer Name</th>
        <th width="40%">Purchased Item</th>
        <th width="20%">Purchased Date</th>
        <th width="20%">Price</th>
        </tr>
        {% for row in orders %}
        <tr>
            <td>{{row.id}}</td>
            <td>{{row.customer_name}}</td>
            <td>{{row.purchased_items}}</td>
            <td>{{row.purchased_date}}</td>
            <td>$ {{row.price}}</td>
        </tr>
        {% endfor %}
    </table>
    </div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<script>
$(document).ready(function(){
    $.datepicker.setDefaults({
        dateFormat: 'yy-mm-dd'
    });
    $(function(){
        $("#From").datepicker();
        $("#to").datepicker();
    });
    $('#range').click(function(){
        var From = $('#From').val();
        var to = $('#to').val();
        if(From != '' && to != '')
        {
            $.ajax({
                url:"/range",
                method:"POST",
                data:{From:From, to:to},
                success:function(data)
                {
                    $('#purchase_order').html(data);
                    $('#purchase_order').append(data.htmlresponse);
                }
            });
        }
        else
        {
            alert("Please Select the Date");
        }
    });
});
</script>
</body>
</html>
templates/response.html
//templates/response.html
<table class="table table-bordered">
    <tr>
    <th width="5%">ID</th>
    <th width="35%">Customer Name</th>
    <th width="40%">Purchased Item</th>
    <th width="20%">Purchased Date</th>
    <th width="20%">Price</th>
    </tr>
    {% for row in ordersrange %}
        <tr>
        <td>{{row.id}}</td>
        <td>{{row.customer_name}}</td>
        <td>{{row.purchased_items}}</td>
        <td>{{row.purchased_date}}</td>
        <td>{{row.price}}</td>
        </tr>
    {% endfor %}
</table>

Friday, July 2, 2021

Login Form Using Bootstrap Modal using Python Flask jquery Ajax password hash and session

Login Form Using Bootstrap Modal using Python Flask jquery Ajax password hash and session

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 admin_login (
id serial PRIMARY KEY,
admin_name VARCHAR ( 150 ) NOT NULL,
admin_password VARCHAR ( 150 ) NOT NULL
);

INSERT INTO
    admin_login(admin_name,admin_password)
VALUES
('admin', 'pbkdf2:sha256:150000$FXLDgm3a$bd46f6b7b44124a523f9566d03bf110ba2ebf28bfd3522faeddd56eabebcb7f5');
app.py
 
#app.py
from flask import Flask, render_template, request, jsonify, flash, redirect, session
from werkzeug.security import generate_password_hash, check_password_hash
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():
    hash = generate_password_hash('cairocoders')
    check_hash = check_password_hash(hash, 'cairocoders')   
    return render_template('index.html', hash=hash, check_hash=check_hash)
 
@app.route("/action",methods=["POST","GET"])
def action(): 
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        print(username)
        print(password)
        cur.execute("SELECT * FROM admin_login WHERE admin_name = %s", [username,])
        total_row = cur.rowcount
        print(total_row)

        if total_row > 0:
            data = cur.fetchone()
            rs_password = data['admin_password']
            print(rs_password)
            if check_password_hash(rs_password, password):
                session['logged_in'] = True
                session['username'] = username
                msg = 'success'
            else:
               msg = 'No-data'
        else:
            msg = 'No-data'   
    return jsonify(msg)   
 
@app.route('/logout')
def logout():
    session.clear()
    return redirect('/')

if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>  
 <html>  
<head>  
<title>Login Form Using Bootstrap Modal using Python Flask jquery Ajax password hash and session</title>  
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>  
<body>  
<div class="container" style="width:700px;">  
                <h3 align="center">Login Form Using Bootstrap Modal using Python Flask jquery Ajax password hash and session</h3><br />  
                <br />  
                <br />  
                <!--<p>hash : {{ hash }}</p>
                <p>hash : {{ check_hash }}</p> -->
                <br />  
                <br />  
                <br />  
                {% if session.logged_in %}
                <div align="center">  
                     <h1>Welcome - {{session.username}}</h1><br />  
                     <a href="/logout">Logout</a>  
                </div>  
                {% else %}  
                <div align="center">  
                     <a data-target="#myModal" role="button" class="btn btn-warning" data-toggle="modal"><span class="glyphicon glyphicon-hand-up"></span>Login</a>
                </div>  
                {% endif %} 
           </div>  
           <br />  
             
 <div id="myModal" class="modal fade">  
      <div class="modal-dialog">  
   <!-- Modal content-->  
           <div class="modal-content">  
                <div class="modal-header">  
                     <button type="button" class="close" data-dismiss="modal">×</button>  
                     <h4 class="modal-title">Login Form Using Bootstrap Modal using Python Flask jquery Ajax password hash and session</h4>  
                </div>  
                <div class="modal-body">  
                     <label>Username</label>  
                     <input type="text" name="username" id="username" class="form-control" />  
                     <br />  
                     <label>Password</label>  
                     <input type="password" name="password" id="password" class="form-control" />  
                     <br />  
                     <button type="button" name="login_button" id="login_button" class="btn btn-warning">Login</button>  
                </div>  
           </div>  
      </div>  
 </div>  
 <script>  
 $(document).ready(function(){  
      $('#login_button').click(function(){  
           var username = $('#username').val();  
           var password = $('#password').val();  
           if(username != '' && password != '')  
           {  
                $.ajax({  
                     url:"/action",  
                     method:"POST",  
                     data: {username:username, password:password},  
                     success:function(data)  
                     {  
                          alert(data);  
                          if(data == 'No-data')  
                          {  
                               alert("Invalid Email Or Password!");  
                          }  
                          else 
                          {  
                               $('#loginModal').hide();  
                               location.reload();  
                          }  
                     }  
                });  
           }  
           else 
           {  
                alert("Both Fields are required");  
           }  
      });    
 });  
</script>   
</body>  
 </html>  
 

Multiple Select option using Python Flask Jquery Ajax and PostgreSQL database

Multiple Select option using Python Flask Jquery Ajax and PostgreSQL database

Python Flask Multiple Select option using Bootstrap Select Plugin and Jquery Ajax 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

bootstrap select https://developer.snapappointments.com/bootstrap-select/examples/

CREATE TABLE programming (
id serial PRIMARY KEY,
title VARCHAR ( 150 ) NOT NULL
);

INSERT INTO
    programming(title)
VALUES
('Python Flask'),
('Python Django'),
('Express.js'),
('Laravel'),
('Spring'),
('Angular'),
('React'),
('Vue');

CREATE TABLE skills (
id serial PRIMARY KEY,
skillname VARCHAR ( 150 ) NOT NULL
);


app.py
#app.py
from flask import Flask, render_template, request, jsonify
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(): 
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    cur.execute("SELECT * FROM programming ORDER BY id")
    programming = cur.fetchall()  
    return render_template('index.html', programming = programming)
 
@app.route("/ajax_add",methods=["POST","GET"])
def ajax_add():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    if request.method == 'POST':
        hidden_skills = request.form['hidden_skills']
        print(hidden_skills)     
        cur.execute("INSERT INTO skills (skillname) VALUES (%s)",[hidden_skills])
        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>Multiple Select option using Python Flask Jquery Ajax and PostgreSQL database</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/css/bootstrap-select.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/js/bootstrap-select.min.js"></script>
</head>
<body>
<br /><br />
<div class="container">
   <br />
   <h2 align="center">Multiple Select option using Python Flask Jquery Ajax and PostgreSQL database</h2>
   <br />
    <div class="col-md-4" style="margin-left:200px;">
		<form method="post" id="multiple_select_form">
		<select name="skills" id="skills" class="form-control selectpicker" data-live-search="true" multiple>
			{% for row in programming %}
			<option value="{{row.title}}">{{row.title}}</option>
			{% endfor %}
		</select>
		<br /><br />
		<input type="hidden" name="hidden_skills" id="hidden_skills" />
		<input type="submit" name="submit" class="btn btn-info" value="Submit" />
		</form>
    <br />
   </div>
</div>
<script>
$(document).ready(function(){
    $('.selectpicker').selectpicker();
     
    $('#skills').change(function(){
      $('#hidden_skills').val($('#skills').val());
    });
     
    $('#multiple_select_form').on('submit', function(event){
		event.preventDefault();
		if($('#skills').val() != '')
		{
			var form_data = $(this).serialize();
			$.ajax({
				url:"/ajax_add",
				method:"POST",
				data:form_data,
				success:function(data)
				{
				//console.log(data);
				$('#hidden_skills').val('');
				$('.selectpicker').selectpicker('val', '');
				alert(data);
				}
			})
		}
		else
		{
			alert("Please select framework");
			return false;
		}
    });
});
</script>
</body>
</html>

Thursday, July 1, 2021

Fullcalandar CRUD(Create, Read, Update, Delete) with Python Flask Jquery Ajax and PostgreSQL

Fullcalandar CRUD(Create, Read, Update, Delete) with Python Flask Jquery Ajax and PostgreSQL

This tutorial is a Jquery Fullcalandar Integration FullCalendar.js plugin https://fullcalendar.io/demos

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 events (
id serial PRIMARY KEY,
title VARCHAR ( 150 ) NOT NULL,
start_event TIMESTAMP NOT NULL,
end_event TIMESTAMP NOT NULL
);

INSERT INTO
    events(title,start_event,end_event)
VALUES
('Python Flask coding visual studio', '2021-07-03 16:00:00', '2021-07-04 03:00:00'),
('PHP coding Notepad++', '2021-07-08 03:17:15', '2021-07-10 04:00:00'),
('Basketball', '2021-07-05 00:00:00', '2021-07-05 14:30:00'),
('Birthday Party', '2021-07-12 00:00:00', '2021-07-13 00:00:00');
app.py
 
#app.py
from flask import Flask, render_template, request, jsonify
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():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    cur.execute("SELECT * FROM events ORDER BY id")
    calendar = cur.fetchall()  
    return render_template('index.html', calendar = calendar)
 
@app.route("/insert",methods=["POST","GET"])
def insert():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    if request.method == 'POST':
        title = request.form['title']
        start = request.form['start']
        end = request.form['end']
        print(title)     
        print(start)  
        cur.execute("INSERT INTO events (title,start_event,end_event) VALUES (%s,%s,%s)",[title,start,end])
        conn.commit()       
        cur.close()
        msg = 'success'  
    return jsonify(msg)
 
@app.route("/update",methods=["POST","GET"])
def update():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    if request.method == 'POST':
        title = request.form['title']
        start = request.form['start']
        end = request.form['end']
        id = request.form['id']
        print(title)     
        print(start)  
        cur.execute("UPDATE events SET title = %s, start_event = %s, end_event = %s WHERE id = %s ", [title, start, end, id])
        conn.commit()       
        cur.close()
        msg = 'success'  
    return jsonify(msg)    
 
@app.route("/ajax_delete",methods=["POST","GET"])
def ajax_delete():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    if request.method == 'POST':
        getid = request.form['id']
        print(getid)
        cur.execute('DELETE FROM events WHERE id = {0}'.format(getid))
        conn.commit()       
        cur.close()
        msg = 'Record deleted successfully'  
    return jsonify(msg) 
 
if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html>
 <head>
  <title>Fullcalandar CRUD(Create, Read, Update, Delete) with Python Flask Jquery Ajax and PostgreSQL</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.css" />
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.min.js"></script>
  <script>
  $(document).ready(function() {
   var calendar = $('#calendar').fullCalendar({
    editable:true,
    header:{
     left:'prev,next today',
     center:'title',
     right:'month,agendaWeek,agendaDay'
    },
    events: [{% for row in calendar %}{ id : '{{row.id}}', title : '{{row.title}}', start : '{{row.start_event}}', end : '{{row.end_event}}', }, {% endfor %}],
    selectable:true,
    selectHelper:true,
    select: function(start, end, allDay)
    {
     var title = prompt("Enter Event Title");
     if(title)
     {
      var start = $.fullCalendar.formatDate(start, "Y-MM-DD HH:mm:ss");
      var end = $.fullCalendar.formatDate(end, "Y-MM-DD HH:mm:ss");
      $.ajax({
       url:"/insert",
       type:"POST",
       data:{title:title, start:start, end:end},
       success:function(data)
       {
         //alert(data)
        alert("Added Successfully");
        window.location.replace("/");
       }
      })
     }
    },
    editable:true,
    eventResize:function(event)
    {
     var start = $.fullCalendar.formatDate(event.start, "Y-MM-DD HH:mm:ss");
     var end = $.fullCalendar.formatDate(event.end, "Y-MM-DD HH:mm:ss");
     var title = event.title;
     var id = event.id;
     $.ajax({
      url:"/update",
      type:"POST",
      data:{title:title, start:start, end:end, id:id},
      success:function(){
       calendar.fullCalendar('refetchEvents');
       alert('Event Update');
      }
     })
    },
     
    eventDrop:function(event)
    {
     var start = $.fullCalendar.formatDate(event.start, "Y-MM-DD HH:mm:ss");
     var end = $.fullCalendar.formatDate(event.end, "Y-MM-DD HH:mm:ss");
     var title = event.title;
     var id = event.id;
     $.ajax({
      url:"/update",
      type:"POST",
      data:{title:title, start:start, end:end, id:id},
      success:function()
      {
       calendar.fullCalendar('refetchEvents');
       alert("Event Updated");
      }
     });
    },
 
    eventClick:function(event)
    {
     if(confirm("Are you sure you want to remove it?"))
     {
      var id = event.id;
      $.ajax({
       url:"/ajax_delete",
       type:"POST",
       data:{id:id},
       success:function()
       {
        calendar.fullCalendar('refetchEvents');
        alert("Event Removed");
       }
      })
     }
    },
 
   });
  });
    
  </script>
 </head>
 <body>
  <br />
  <h2 align="center"><a href="#">Fullcalandar CRUD(Create, Read, Update, Delete) with Python Flask Jquery Ajax and PostgreSQL</a></h2>
  <br />
  <div class="container">
   <div id="calendar"></div>
  </div>
 </body>
</html>

Wednesday, June 30, 2021

Live Poll using Jquery ajax and Python Flask PosgreSQL

Live Poll using Jquery ajax and Python Flask PosgreSQL

CREATE TABLE tblprogramming (
id serial PRIMARY KEY,
title VARCHAR ( 150 ) NOT NULL
);

INSERT INTO
    tblprogramming(title)
VALUES
('Flask'),
('Laravel'),
('React.js'),
('Express'),
('Django');

CREATE TABLE tbl_poll (
id serial PRIMARY KEY,
web_framework VARCHAR ( 150 ) NOT NULL
);

INSERT INTO
    tbl_poll(web_framework)
VALUES
('Flask'),
('Flask'),
('Flask'),
('Express'),
('React.js'),
('Laravel'),
('Flask'),
('Flask'),
('Laravel'),
('Django'),
('Django'),
('Flask');


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
app.py
 
#app.py
from flask import Flask, render_template, request, jsonify, flash, redirect
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():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    cur.execute("SELECT * FROM tblprogramming ORDER BY id ASC")
    webframework = cur.fetchall()  
    return render_template('index.html', webframework = webframework)
 
@app.route("/polldata",methods=["POST","GET"])
def polldata():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor) 
    query = "SELECT * from tbl_poll"
    cur.execute(query)
    total_poll_row = int(cur.rowcount) 
    cur.execute("SELECT * FROM tblprogramming ORDER BY id ASC")
    framework = cur.fetchall()  
    frameworkArray = []
    for row in framework:
        get_title = row['title']
        cur.execute("SELECT * FROM tbl_poll WHERE web_framework = %s", [get_title])
        row_poll = cur.fetchone()  
        total_row = cur.rowcount
        #print(total_row)
        percentage_vote = round((total_row/total_poll_row)*100)
        print(percentage_vote)
        if percentage_vote >= 40:
            progress_bar_class = 'progress-bar-success'
        elif percentage_vote >= 25 and percentage_vote < 40:   
            progress_bar_class = 'progress-bar-info'  
        elif percentage_vote >= 10 and percentage_vote < 25:
            progress_bar_class = 'progress-bar-warning'
        else:
            progress_bar_class = 'progress-bar-danger'
  
        frameworkObj = {
                'id': row['id'],
                'name': row['title'],
                'percentage_vote': percentage_vote,
                'progress_bar_class': progress_bar_class}
        frameworkArray.append(frameworkObj)
    return jsonify({'htmlresponse': render_template('response.html', frameworklist=frameworkArray)})
 
@app.route("/insert",methods=["POST","GET"])
def insert():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    if request.method == 'POST':
        poll_option = request.form['poll_option']
        print(poll_option)      
        cur.execute("INSERT INTO tbl_poll (web_framework) VALUES (%s)",[poll_option])
        conn.commit()       
        cur.close()
        msg = 'success' 
    return jsonify(msg)
 
if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<html>  
<head>  
<title>Live Poll using Jquery ajax and Python Flask PosgreSQL</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
</head>  
    <body>  
        <div class="container">  
            <br />  <br />
            <h2 align="center">Live Poll using Jquery ajax and Python Flask PosgreSQL </h2><br />
            <div class="row">
                <div class="col-md-6">
                    <form method="post" id="poll_form">
                        <h3>Which is Best Web Development Frameworks</h3>
                        <br />
                        {% for row in webframework %}
                        <div class="radio">
                            <label><h4><input type="radio" name="poll_option" class="poll_option" value="{{row.title}}" /> {{row.title}}</h4></label>
                        </div>
                        {% endfor %}
                        <br />
                        <input type="submit" name="poll_button" id="poll_button" class="btn btn-primary" />
                    </form>
                    <br />
                </div>
                <div class="col-md-6">
                    <br />
                    <br />
                    <h4>Live Poll Result</h4><br />
                    <div id="poll_result"></div>
                </div>
            </div>
        </div>
<script>  
$(document).ready(function(){
    fetch_poll_data();
    function fetch_poll_data()
    { 
        var fetchall = 'all';
        var dataString = 'fetchall='+ fetchall;
        $.ajax({
            url:"/polldata",
            method:"POST",
            data: dataString,
            success:function(data)
            {
                $('#poll_result').html(data); 
                $("#poll_result").append(data.htmlresponse);
            }
        });
    }
    $('#poll_form').on('submit', function(event){
        event.preventDefault();
        var poll_option = '';
        $('.poll_option').each(function(){
            if($(this).prop("checked"))
            {
                poll_option = $(this).val();
            }
        });
        if(poll_option != '')
        {
            $('#poll_button').attr('disabled', 'disabled');
            var form_data = $(this).serialize();
            $.ajax({
                url:"/insert",
                method:"POST",
                data:form_data,
                success:function()
                {
                    $('#poll_form')[0].reset();
                    $('#poll_button').attr('disabled', false);
                    fetch_poll_data();
                    alert("Poll Submitted Successfully");
                }
            });
        }
        else
        {
            alert("Please Select Option");
        }
    });
});  
</script>
</body>  
</html>
templates/response.html
//templates/response.html
{% for row in frameworklist %}  
<div class="row">
    <div class="col-md-2" align="right">
        <label>{{row.name}}</label>
    </div>
    <div class="col-md-10">
        <div class="progress">
            <div class="progress-bar {{row.progress_bar_class}}" role="progressbar" aria-valuenow="{{row.percentage_vote}}" aria-valuemin="0" aria-valuemax="100" style="width:{{row.percentage_vote}}%">
                {{row.percentage_vote}} % programmer like <b>{{row.name}}</b> Web Framework
            </div>
        </div>
    </div>
</div>
{% endfor %} 

Monday, June 28, 2021

File Upload Progress Bar using JQuery Ajax Python Flask PostgreSQL Database

File Upload Progress Bar using JQuery Ajax Python Flask PostgreSQL Database

CREATE TABLE uploads (
id serial PRIMARY KEY,
file_name VARCHAR ( 150 ) NOT NULL,
upload_time TIMESTAMP NOT NULL
);

jQuery Form Plugin allows you to easily and unobtrusively upgrade HTML forms to use AJAX.

https://github.com/jquery-form/form
bootstrap progressbar https://getbootstrap.com/docs/4.0/components/progress/

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
app.py
 
#app.py
from flask import Flask, render_template, request, jsonify
from werkzeug.utils import secure_filename
import os
from datetime import datetime

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.config['UPLOAD_FOLDER'] = 'static/uploads'
   
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
   
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
 
@app.route('/')
def index(): 
    return render_template('index.html')
 
@app.route("/upload",methods=["POST","GET"])
def upload():
    file = request.files['uploadFile']
    filename = secure_filename(file.filename)
    if file and allowed_file(file.filename):
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        filenameimage = file.filename
 
        today = datetime.today() 
        cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
        cur.execute("INSERT INTO uploads (file_name,upload_time) VALUES (%s,%s)",[filenameimage,today])
        conn.commit()       
        cur.close()
        msg  = 'File successfully uploaded ' + file.filename + ' to the database!'
    else:
        msg  = 'Invalid Uplaod only png, jpg, jpeg, gif'
    return jsonify({'htmlresponse': render_template('response.html', msg=msg, filenameimage=filenameimage)})
    
if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html>
<head>
<title>File Upload Progress Bar using JQuery Ajax Python Flask PostgreSQL Database</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.3.0/jquery.form.min.js" integrity="sha384-qlmct0AOBiA2VPZkMY3+2WqkHtIQ9lSdAsAn5RUJD/3vA5MKDgSGcdmIv4ycVxyn" crossorigin="anonymous"></script>
<!--<script src="/static/js/jquery.form.js"></script>-->
</head>
    <body>
        <div class="container">
            <br />
            <h3 align="center">File Upload Progress Bar using JQuery Ajax Python Flask PostgreSQL Database</h3>
            <br />
            <div class="panel panel-default">
                <div class="panel-heading"><b>Ajax File Upload Progress Bar using JQuery Ajax</b></div>
                <div class="panel-body">
                    <form id="uploadImage" action="/upload" method="post">
                        <div class="form-group">
                            <label>File Upload</label>
                            <input type="file" name="uploadFile" id="uploadFile" accept=".jpg, .png" />
                        </div>
                        <div class="form-group">
                            <input type="submit" id="uploadSubmit" value="Upload" class="btn btn-info" />
                        </div>
                        <div class="progress">
                            <div class="progress-bar progress-bar-striped bg-success" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
                        </div>
                        <div id="targetLayer" style="display:none;"></div>
                    </form>
                    <div id="loader-icon" style="display:none;"><img src="/static/images/loader.gif" /></div>
                </div>
            </div>
        </div>
<script>
$(document).ready(function(){
    $('#uploadImage').submit(function(event){
        if($('#uploadFile').val()){
            event.preventDefault();
            $('#loader-icon').show();
            $('#targetLayer').hide();
            $(this).ajaxSubmit({
                target: '#targetLayer',
                beforeSubmit:function(){
                    $('.progress-bar').width('50%');
                },
                uploadProgress: function(event, position, total, percentageComplete)
                {
                    $('.progress-bar').animate({
                        width: percentageComplete + '%'
                    }, {
                        duration: 1000
                    });
                },
                success:function(data){
                    $('#loader-icon').hide();
                    $('#targetLayer').show();
                    $('#targetLayer').append(data.htmlresponse);
                },
                resetForm: true
            });
        }
        return false;
    });
});
</script>
</body>
</html>
templates/response.html
//templates/response.html
<p><b>{{ msg }}</b></p>
<img src="/static/uploads/{{ filenameimage }}" class="img-thumbnail" width="300" height="250" />

Sunday, June 27, 2021

Price Range Product Filters Using Jquery Ajax Python Flask and PostgreSQL

Price Range Product Filters Using Jquery Ajax Python Flask and PostgreSQL

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 product (
pid serial PRIMARY KEY,
name VARCHAR ( 70 ) NOT NULL,
image VARCHAR ( 255 ) NOT NULL,
category VARCHAR ( 70 ) NOT NULL,
price INT NOT NULL
);

INSERT INTO
    product(name,image,category,price)
VALUES
('Samsung Galaxy A10S', '1.jpg', 'Mobile', 520),
('HP Laptop - 17z-ca100 ', '2.jpg', 'Laptop', 1600),
('3 IN 1 CAR VOLTMETER', '3.jpg', 'Car', 2020),
('Gucci G-Timeless', '4.jpg', 'Watch', 320),
('Infinix Hot S3', '5.jpg', 'Mobile', 150),
('VIVO V9 Youth', '6.jpeg', 'Laptop', 3500),
('Moto E4 Plus', '7.jpeg', 'Car', 250),
('Lenovo K8 Plus', '8.jpeg', 'Watch', 4500);
app.py
 
#app.py
from flask import Flask, render_template, request, jsonify
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("/fetchrecords",methods=["POST","GET"])
def fetchrecords():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    if request.method == 'POST':
        query = request.form['action']
        minimum_price = request.form['minimum_price']
        maximum_price = request.form['maximum_price']
        #print(query)
        if query == '':
            cur.execute("SELECT * FROM product ORDER BY pid ASC")
            productlist = cur.fetchall()
            print('all list')
        else:
            cur.execute("SELECT * FROM product WHERE price BETWEEN (%s) AND (%s)", [minimum_price, maximum_price])
            productlist = cur.fetchall()  
    return jsonify({'htmlresponse': render_template('response.html', productlist=productlist)})
 
if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html>
<head>
<title>Price Range Product Filters Using Jquery Ajax Python Flask and PostgreSQL</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<div class="container">
    <div class="row">
    <br />
    <h2 align="center">Price Range Product Filters Using Jquery Ajax Python Flask and PostgreSQL</h2>
    <br />
        <div class="col-md-3">                                
            <div class="list-group">
                <h3>Price</h3>
                <input type="hidden" id="hidden_minimum_price" value="0" />
                <input type="hidden" id="hidden_maximum_price" value="65000" />
                <p id="price_show">10 - 5000</p>
                <div id="price_range"></div>
            </div>                
        </div>
        <div class="col-md-9">
           <div class="row filter_data">
        </div>
    </div>
    </div>
</div>
<style>
#loading
{
    text-align:center; 
    background: url('images/loading.gif') no-repeat center; 
    height: 150px;
}
</style>
<script>
$(document).ready(function(){
    filter_data();
    function filter_data()
    {
        $('.filter_data').html('<div id="loading" style="" ></div>');
        var action = 'fetch_data';
        var minimum_price = $('#hidden_minimum_price').val();
        var maximum_price = $('#hidden_maximum_price').val();
        $.ajax({
            url:"/fetchrecords",
            method:"POST",
            data:{action:action, minimum_price:minimum_price, maximum_price:maximum_price},
            success:function(data){
                $('.filter_data').html(data);
                $(".filter_data").append(data.htmlresponse);
            }
        });
    }
    $('#price_range').slider({
        range:true,
        min:50,
        max:5000,
        values:[50, 5000],
        step:50,
        stop:function(event, ui)
        {
            $('#price_show').html(ui.values[0] + ' - ' + ui.values[1]);
            $('#hidden_minimum_price').val(ui.values[0]);
            $('#hidden_maximum_price').val(ui.values[1]);
            filter_data();
        }
    });
});
</script>
</body>
</html>
templates/response.html
//templates/response.html
{% for row in productlist %}  
<div class="col-sm-4 col-lg-3 col-md-3">
    <div style="border:1px solid #ccc; border-radius:5px; padding:16px; margin-bottom:16px; height:300px;">
        <img src="/static/images/{{row.image}}" alt="" class="img-responsive" >
        <p align="center"><strong><a href="#">{{row.name}}</a></strong></p>
        <h4 style="text-align:center;" class="text-danger" >{{row.price}}</h4>
    </div>
</div>
{% endfor %} 

Saturday, June 26, 2021

Delete Multiple Records using Jquey Ajax Python Flask PostgreSQL

Delete Multiple Records using Jquey Ajax Python Flask PostgreSQL

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

this post a user select multiple records using checkbox fields and click the delete button a loading image gif show and a successfully message display and animate effect every row selected without refresh the page

https://github.com/jquery-form/form

The jQuery Form Plugin allows you to easily and unobtrusively upgrade HTML forms to use AJAX. The main methods, ajaxForm and ajaxSubmit, gather information from the form element to determine how to manage the submit process. Both of these methods support numerous options which allow you to have full control over how the data is submitted.

CREATE TABLE employee (
id serial PRIMARY KEY,
name VARCHAR ( 100 ) NOT NULL,
position VARCHAR ( 100 ) NOT NULL,
office VARCHAR ( 100 ) NOT NULL,
age INT NOT NULL,
salary INT NOT NULL,
photo VARCHAR ( 150 ) NOT NULL,
);


INSERT INTO
    employee(name, position, office, age, salary, photo)
VALUES
('Tiger Wood', 'Accountant', 'Tokyo', 36, 5689, '01.jpg'),
('Mark Oto Ednalan', 'Chief Executive Officer (CEO)', 'London', 56, 5648, '02.jpg'),
('Jacob thompson', 'Junior Technical Author', 'San Francisco', 23, 5689, '03.jpg'),
('cylde Ednalan', 'Software Engineer', 'Olongapo', 23, 54654, '04.jpg'),
('Rhona Davidson', 'Software Engineer', 'San Francisco', 26, 5465, '05.jpg'),
('Quinn Flynn', 'Integration Specialist', 'New York', 53, 56465, '06.jpg'),
('Tiger Nixon', 'Software Engineer', 'London', 45, 456, '07.jpg'),
('Airi Satou', 'Pre-Sales Support', 'New York', 25, 4568, '08.jpg'),
('Angelica Ramos', 'Sales Assistant', 'New York', 45, 456, '09.jpg'),
('Ashton updated', 'Senior Javascript Developer', 'Olongapo', 45, 54565, '01.jpg'),
('Bradley Greer', 'Regional Director', 'San Francisco', 27, 5485, '02.jpg'),
('Brenden Wagner', 'Javascript Developer', 'San Francisco', 38, 65468, '03.jpg'),
('Brielle Williamson', 'Personnel Lead', 'Olongapo', 56, 354685, '04.jpg'),
('Bruno Nash', 'Customer Support', 'New York', 36, 65465, '05.jpg'),
('cairocoders', 'Sales Assistant', 'Sydney', 45, 56465, '06.jpg'),
('Zorita Serrano', 'Support Engineer', 'San Francisco', 38, 6548, '07.jpg'),
('Zenaida Frank', 'Chief Operating Officer (COO)', 'San Francisco', 39, 545, '08.jpg'),
('Sakura Yamamoto', 'Support Engineer', 'Tokyo', 48, 5468, '05.jpg'),
('Serge Baldwin', 'Data Coordinator', 'Singapore', 85, 5646, '05.jpg'),
('Shad Decker', 'Regional Director', 'Tokyo', 45, 4545, '05.jpg');
app.py
 
#app.py
from flask import Flask, render_template, request, jsonify
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(): 
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    cur.execute("SELECT * FROM employee ORDER BY id DESC")
    employeelist = cur.fetchall()
    return render_template('index.html', employeelist=employeelist)
 
@app.route("/delete",methods=["POST","GET"])
def delete():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    for getid in request.form.getlist('checkdelete'):
        print(getid)
        cur.execute('DELETE FROM employee WHERE id = {0}'.format(getid))
        conn.commit()      
    cur.close()
    return jsonify('Records deleted successfully')
    
if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html>
<head>
<title>Delete Multiple Records using Jquey Ajax Python Flask PostgreSQL</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.3.0/jquery.form.min.js" integrity="sha384-qlmct0AOBiA2VPZkMY3+2WqkHtIQ9lSdAsAn5RUJD/3vA5MKDgSGcdmIv4ycVxyn" crossorigin="anonymous"></script>
</head>  
    <body>  
        <div class="container">  
            <br />
   <div class="table-responsive">  
    <h3 align="center">Delete Multiple Records using Jquey Ajax Python Flask PostgreSQL</h3><br />
    <div class="table-responsive">
        <div id="targetLayer" class="btn btn-success" style="display:none;width:100%;margin-bottom: 10px;"></div>
        <div id="loader-icon" style="display:none;"><img src="/static/img/loader.gif" /></div>
        <form id="deleteall" action="/delete" method="post">
                    <table class="table table-bordered">
                        <thead>
                        <tr>
                            <th width="5%">
                                <input type="submit" value="Delete" name="delete_all" id="delete_all" class="btn btn-danger btn-xs" />
                            <th>Name</th>
                            <th>Position</th>
                            <th>Office</th>
                            <th>Age</th>
                            <th>Salary</th>
                        </tr>
                        </thead>
                        {% for row in employeelist %}
                            <tr>
                                <td>
                                    <input type="checkbox" name="checkdelete" id="checkdelete" class="delete_checkbox" value="{{row.id}}" />
                                </td>
                                <td>{{row.name}}</td>
                                <td>{{row.position}}</td>
                                <td>{{row.office}}</td>
                                <td>{{row.age}}</td>
                                <td>$ {{ "%.2f"|format(row.salary) }}</td>
                            </tr>
                        {% endfor %}    
                    </table>
        </form>        
                </div>
   </div>  
  </div>
<style>
.removeRow {background-color: #64b418;color:#FFFFFF;}
</style>
<script>  
$(document).ready(function(){ 
    $('.delete_checkbox').click(function(){
        if($(this).is(':checked')) {
            $(this).closest('tr').addClass('removeRow');
        }else{
            $(this).closest('tr').removeClass('removeRow');
        }
    });
    $('#deleteall').submit(function(event){
        if($('#checkdelete').val()){
            event.preventDefault();
            $('#loader-icon').show();
            $('#targetLayer').hide();
            $(this).ajaxSubmit({
                target: '#targetLayer',
                success:function(data){
                    $('.removeRow').fadeOut(1500);
                    $('#loader-icon').hide();
                    $('#targetLayer').show();
                    $('#targetLayer').html(data);
                },
                resetForm: true
            });
        }
        return false;
    });
});  
</script>
</body>  
</html> 

Editable Select Box using Python Flask jQuery Ajax and PostgreSQL Database

Editable Select Box using Python Flask jQuery Ajax and PostgreSQL Database

jQuery Editable Select is a jQuery plugin that transforms a select into an input field where single elements are shown in real-time according to the entered characters. It scales down to a real select list when javascript is not available.

https://github.com/indrimuska/jquery-editable-select

See demos here: http://indrimuska.github.io/jquery-editable-select/

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 countries (
id serial PRIMARY KEY,
name VARCHAR ( 60 ) NOT NULL
);

INSERT INTO
    countries(id,name)
VALUES
(1, 'Afghanistan'),
(2, 'Aringland Islands'),
(3, 'Albania'),
(4, 'Algeria'),
(5, 'American Samoa'),
(6, 'Andorra'),
(7, 'Angola'),
(8, 'Anguilla'),
(9, 'Antarctica'),
(10, 'Antigua and Barbuda'),
(11, 'Argentina'),
(12, 'Armenia'),
(13, 'Aruba'),
(14, 'Australia'),
(15, 'Austria'),
(16, 'Azerbaijan'),
(17, 'Bahamas'),
(18, 'Bahrain'),
(19, 'Bangladesh'),
(20, 'Barbados'),
(21, 'Belarus'),
(22, 'Belgium'),
(23, 'Belize'),
(24, 'Benin'),
(25, 'Bermuda'),
(26, 'Bhutan'),
(27, 'Bolivia'),
(28, 'Bosnia and Herzegovina'),
(29, 'Botswana'),
(30, 'Bouvet Island'),
(31, 'Brazil'),
(32, 'British Indian Ocean territory'),
(33, 'Brunei Darussalam'),
(34, 'Bulgaria'),
(35, 'Burkina Faso'),
(36, 'Burundi'),
(37, 'Cambodia'),
(38, 'Cameroon'),
(39, 'Canada'),
(40, 'Cape Verde'),
(41, 'Cayman Islands'),
(42, 'Central African Republic'),
(43, 'Chad'),
(44, 'Chile'),
(45, 'China'),
(46, 'Christmas Island'),
(47, 'Cocos (Keeling) Islands'),
(48, 'Colombia'),
(49, 'Comoros'),
(50, 'Congo'),
(51, 'Congo'),
(52, ' Democratic Republic'),
(53, 'Cook Islands'),
(54, 'Costa Rica'),
(55, 'Ivory Coast (Ivory Coast)'),
(56, 'Croatia (Hrvatska)'),
(57, 'Cuba'),
(58, 'Cyprus'),
(59, 'Czech Republic'),
(60, 'Denmark'),
(61, 'Djibouti'),
(62, 'Dominica'),
(63, 'Dominican Republic'),
(64, 'East Timor'),
(65, 'Ecuador'),
(66, 'Egypt'),
(67, 'El Salvador'),
(68, 'Equatorial Guinea'),
(69, 'Eritrea'),
(70, 'Estonia'),
(71, 'Ethiopia'),
(72, 'Falkland Islands'),
(73, 'Faroe Islands'),
(74, 'Fiji'),
(75, 'Finland'),
(76, 'France'),
(77, 'French Guiana'),
(78, 'French Polynesia'),
(79, 'French Southern Territories'),
(80, 'Gabon'),
(81, 'Gambia'),
(82, 'Georgia'),
(83, 'Germany'),
(84, 'Ghana'),
(85, 'Gibraltar'),
(86, 'Greece'),
(87, 'Greenland'),
(88, 'Grenada'),
(89, 'Guadeloupe'),
(90, 'Guam'),
(91, 'Guatemala'),
(92, 'Guinea'),
(93, 'Guinea-Bissau'),
(94, 'Guyana'),
(95, 'Haiti'),
(96, 'Heard and McDonald Islands'),
(97, 'Honduras'),
(98, 'Hong Kong'),
(99, 'Hungary'),
(100, 'Iceland'),
(101, 'India'),
(102, 'Indonesia'),
(103, 'Iran'),
(104, 'Iraq'),
(105, 'Ireland'),
(106, 'Israel'),
(107, 'Italy'),
(108, 'Jamaica'),
(109, 'Japan'),
(110, 'Jordan'),
(111, 'Kazakhstan'),
(112, 'Kenya'),
(113, 'Kiribati'),
(114, 'Korea (north)'),
(115, 'Korea (south)'),
(116, 'Kuwait'),
(117, 'Kyrgyzstan'),
(118, 'Lao People\'s Democratic Republic'),
(119, 'Latvia'),
(120, 'Lebanon'),
(121, 'Lesotho'),
(122, 'Liberia'),
(123, 'Libyan Arab Jamahiriya'),
(124, 'Liechtenstein'),
(125, 'Lithuania'),
(126, 'Luxembourg'),
(127, 'Macao'),
(128, 'Macedonia'),
(129, 'Madagascar'),
(130, 'Malawi'),
(131, 'Malaysia'),
(132, 'Maldives'),
(133, 'Mali'),
(134, 'Malta'),
(135, 'Marshall Islands'),
(136, 'Martinique'),
(137, 'Mauritania'),
(138, 'Mauritius'),
(139, 'Mayotte'),
(140, 'Mexico'),
(141, 'Micronesia'),
(142, 'Moldova'),
(143, 'Monaco'),
(144, 'Mongolia'),
(145, 'Montserrat'),
(146, 'Morocco'),
(147, 'Mozambique'),
(148, 'Myanmar'),
(149, 'Namibia'),
(150, 'Nauru'),
(151, 'Nepal'),
(152, 'Netherlands'),
(153, 'Netherlands Antilles'),
(154, 'New Caledonia'),
(155, 'New Zealand'),
(156, 'Nicaragua'),
(157, 'Niger'),
(158, 'Nigeria'),
(159, 'Niue'),
(160, 'Norfolk Island'),
(161, 'Northern Mariana Islands'),
(162, 'Norway'),
(163, 'Oman'),
(164, 'Pakistan'),
(165, 'Palau'),
(166, 'Palestinian Territories'),
(167, 'Panama'),
(168, 'Papua New Guinea'),
(169, 'Paraguay'),
(170, 'Peru'),
(171, 'Philippines'),
(172, 'Pitcairn'),
(173, 'Poland'),
(174, 'Portugal'),
(175, 'Puerto Rico'),
(176, 'Qatar'),
(177, 'Runion'),
(178, 'Romania'),
(179, 'Russian Federation'),
(180, 'Rwanda'),
(181, 'Saint Helena'),
(182, 'Saint Kitts and Nevis'),
(183, 'Saint Lucia'),
(184, 'Saint Pierre and Miquelon'),
(185, 'Saint Vincent and the Grenadines'),
(186, 'Samoa'),
(187, 'San Marino'),
(188, 'Sao Tome and Principe'),
(189, 'Saudi Arabia'),
(190, 'Senegal'),
(191, 'Serbia and Montenegro'),
(192, 'Seychelles'),
(193, 'Sierra Leone'),
(194, 'Singapore'),
(195, 'Slovakia'),
(196, 'Slovenia'),
(197, 'Solomon Islands'),
(198, 'Somalia'),
(199, 'South Africa'),
(200, 'South Georgia and the South Sandwich Islands'),
(201, 'Spain'),
(202, 'Sri Lanka'),
(203, 'Sudan'),
(204, 'Suriname'),
(205, 'Svalbard and Jan Mayen Islands'),
(206, 'Swaziland'),
(207, 'Sweden'),
(208, 'Switzerland'),
(209, 'Syria'),
(210, 'Taiwan'),
(211, 'Tajikistan'),
(212, 'Tanzania'),
(213, 'Thailand'),
(214, 'Togo'),
(215, 'Tokelau'),
(216, 'Tonga'),
(217, 'Trinidad and Tobago'),
(218, 'Tunisia'),
(219, 'Turkey'),
(220, 'Turkmenistan'),
(221, 'Turks and Caicos Islands'),
(222, 'Tuvalu'),
(223, 'Uganda'),
(224, 'Ukraine'),
(225, 'United Arab Emirates'),
(226, 'United Kingdom'),
(227, 'United States of America'),
(228, 'Uruguay'),
(229, 'Uzbekistan'),
(230, 'Vanuatu'),
(231, 'Vatican City'),
(232, 'Venezuela'),
(233, 'Vietnam'),
(234, 'Virgin Islands (British)'),
(235, 'Virgin Islands (US)'),
(236, 'Wallis and Futuna Islands'),
(237, 'Western Sahara'),
(238, 'Yemen'),
(239, 'Zaire'),
(240, 'Zambia'),
(241, 'Zimbabwe');

CREATE TABLE tbl_user (
id serial PRIMARY KEY,
fullname VARCHAR ( 100 ) NOT NULL,
country VARCHAR ( 100 ) NOT NULL
);
app.py
 
#app.py
from flask import Flask, render_template, request, jsonify
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(): 
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    cur.execute("SELECT * FROM countries ORDER BY name ASC")
    countrylist = cur.fetchall()
    return render_template('index.html', countrylist=countrylist)
 
@app.route("/insert",methods=["POST","GET"])
def insert():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    if request.method == 'POST':
        fullname = request.form['name']
        country = request.form['country']
        cur.execute("INSERT INTO tbl_user (fullname, country) VALUES (%s,%s)",[fullname,country])
        conn.commit()      
        cur.close()
    return jsonify('New Records added successfully')
 
if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html>
<head>
<title>Editable Select Box using Python Flask jQuery Ajax and PostgreSQL Database</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
 
<script src="http://rawgithub.com/indrimuska/jquery-editable-select/master/dist/jquery-editable-select.min.js"></script>
<link href="http://rawgithub.com/indrimuska/jquery-editable-select/master/dist/jquery-editable-select.min.css" rel="stylesheet">
</head>  
<body>  
<div class="container">  
   <br />
   <h2 align="center">Editable Select Box using Python Flask jQuery Ajax and PostgreSQL Database</h2><br />
   <div class="row">
    <div class="col-md-3"></div>
    <div class="col-md-6">
     <form method="post" id="sample_form">
      <div class="form-group">
       <label>Enter Name</label>
       <input type="text" name="name" id="name" class="form-control">
      </div>
      <div class="form-group">
       <label>Select Country</label>
       <select name="country" id="country" class="form-control">
        {% for row in countrylist %}
            <option value="{{row.name}}">{{row.name}}</option>
        {% endfor %} 
       </select>
      </div>
      <div class="form-group">
       <input type="submit" name="Save" id="save" class="btn btn-success" value="Save" />
      </div>
     </form>
    </div>
   </div>
  </div>
  <script>  
$(document).ready(function(){
    $('#country').editableSelect();
  
    $('#sample_form').on('submit', function(event){
        event.preventDefault();
        if($('#name').val() == '') {
           alert("Enter Name");
           return false;
        }else if($('#country').val() == ''){
           alert("Select Country");
           return false;
        }else{
           $.ajax({
                url:"/insert",
                method:"POST",
                data:$(this).serialize(),
                success:function(data)
                {
                 alert(data);
                 $('#sample_form')[0].reset();
                }
           });
        }
    });
});  
</script>
</body>  
</html> 

Friday, June 25, 2021

Display Popups data on mouse hover using Jquery Ajax and Python Flask PostgreSQL database

Display Popups data on mouse hover using Jquery Ajax and Python Flask PostgreSQL database

load dynamic data from the database using jqueryui tooltip

jQuery UI is a curated set of user interface interactions, effects, widgets, and themes built on top of the jQuery JavaScript Library. Whether you're building highly interactive web applications or you just need to add a date picker to a form control, jQuery UI is the perfect choice.

https://jqueryui.com/

Tooltip : https://jqueryui.com/tooltip/

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 employee (
id serial PRIMARY KEY,
name VARCHAR ( 100 ) NOT NULL,
position VARCHAR ( 100 ) NOT NULL,
office VARCHAR ( 100 ) NOT NULL,
age INT NOT NULL,
salary INT NOT NULL,
photo VARCHAR ( 150 ) NOT NULL,
);


INSERT INTO
    employee(name, position, office, age, salary, photo)
VALUES
('Tiger Wood', 'Accountant', 'Tokyo', 36, 5689, '01.jpg'),
('Mark Oto Ednalan', 'Chief Executive Officer (CEO)', 'London', 56, 5648, '02.jpg'),
('Jacob thompson', 'Junior Technical Author', 'San Francisco', 23, 5689, '03.jpg'),
('cylde Ednalan', 'Software Engineer', 'Olongapo', 23, 54654, '04.jpg'),
('Rhona Davidson', 'Software Engineer', 'San Francisco', 26, 5465, '05.jpg'),
('Quinn Flynn', 'Integration Specialist', 'New York', 53, 56465, '06.jpg'),
('Tiger Nixon', 'Software Engineer', 'London', 45, 456, '07.jpg'),
('Airi Satou', 'Pre-Sales Support', 'New York', 25, 4568, '08.jpg'),
('Angelica Ramos', 'Sales Assistant', 'New York', 45, 456, '09.jpg'),
('Ashton updated', 'Senior Javascript Developer', 'Olongapo', 45, 54565, '01.jpg'),
('Bradley Greer', 'Regional Director', 'San Francisco', 27, 5485, '02.jpg'),
('Brenden Wagner', 'Javascript Developer', 'San Francisco', 38, 65468, '03.jpg'),
('Brielle Williamson', 'Personnel Lead', 'Olongapo', 56, 354685, '04.jpg'),
('Bruno Nash', 'Customer Support', 'New York', 36, 65465, '05.jpg'),
('cairocoders', 'Sales Assistant', 'Sydney', 45, 56465, '06.jpg'),
('Zorita Serrano', 'Support Engineer', 'San Francisco', 38, 6548, '07.jpg'),
('Zenaida Frank', 'Chief Operating Officer (COO)', 'San Francisco', 39, 545, '08.jpg'),
('Sakura Yamamoto', 'Support Engineer', 'Tokyo', 48, 5468, '05.jpg'),
('Serge Baldwin', 'Data Coordinator', 'Singapore', 85, 5646, '05.jpg'),
('Shad Decker', 'Regional Director', 'Tokyo', 45, 4545, '05.jpg');

app.py
 
#app.py
from flask import Flask, render_template, request, jsonify
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(): 
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    cur.execute("SELECT * FROM employee ORDER BY id ASC")
    employeelist = cur.fetchall()
    return render_template('index.html', employeelist=employeelist)
 
@app.route("/fetchdata",methods=["POST","GET"])
def fetchdata():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    if request.method == 'POST':
        id = request.form['id']
        cur.execute("SELECT * FROM employee WHERE id = %s", [id])
        rs = cur.fetchone() 
        name = rs['name']
        photo = rs['photo']
        position = rs['position']
        office = rs['office']
        print(photo)
    return jsonify({'htmlresponse': render_template('response.html', name=name, photo=photo, position=position, office=office)})

if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html>
<head>
<title>Display Popups data on mouse hover using Jquery Ajax and Python Flask PostgreSQL database </title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
 
<link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<body>  
<div class="container">
   <br />
   <h3 align="center">Display Popups data on mouse hover using Jquery Ajax and Python Flask PostgreSQL database </a></h3><br />
   <br />
   <div class="row">
    <div class="col-md-12">
        <div class="panel-body">
            <div class="table-responsive">
                <table class="table table-bordered">
                    <thead>
                        <tr>
                            <th width="60">Photo</th>
                            <th>Name</th>
                            <th>Position</th>
                            <th>Office</th>
                            <th>Age</th>
                            <th>Salary</th>
                        </tr>
                        </thead> 
                        {% for row in employeelist %}
                            <tr>
                                <td><a href="#" id="{{row.id}}" title=" "><img src="/static/images/{{row.photo}}" height="50" width="50"/></a></td>
                                <td>{{row.name}}</td>
                                <td>{{row.position}}</td>
                                <td>{{row.office}}</td>
                                <td>{{row.age}}</td>
                                <td>{{row.salary}}</td>
                            </tr>
                        {% endfor %} 
                </table>
            </div>
      </div>
     </div>
    </div>
  </div>
<script>  
$(document).ready(function(){ 
    $('a').tooltip({
        classes:{
            "ui-tooltip":"highlight"
        },
        position:{ my:'left center', at:'right+50 center'},
        content:function(result){
            $.post('/fetchdata', {
                id:$(this).attr('id')
            }, function(data){
                result(data.htmlresponse);
                 
            });
        }
    });
});  
</script>
</body>  
</html>
templates/response.html
//templates/response.html
<p align="center"><img src="/static/images/{{photo}}" class="img-thumbnail" /></p>
<p>Name : {{ name }}</p>
<p>Position : {{ position }}</p>
<p>Office : {{ office }}</p>

Thursday, June 24, 2021

Sign Up Form Validation using jqBootstrapValidation using Python Flask Jquery Ajax and PostgreSQL

Sign Up Form Validation using jqBootstrapValidation using Python Flask Jquery Ajax and PostgreSQL

jqBootstrapValidation https://reactiveraven.github.io/jqBootstrapValidation/

A JQuery validation plugin for bootstrap forms.

CREATE TABLE users (
id serial PRIMARY KEY,
fullname VARCHAR ( 100 ) NOT NULL,
username VARCHAR ( 50 ) NOT NULL,
password VARCHAR ( 255 ) NOT NULL,
email VARCHAR ( 50 ) NOT NULL
);

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
app.py
 
#app.py
from flask import Flask, render_template, request, jsonify
from werkzeug.security import generate_password_hash, check_password_hash
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("/insert",methods=["POST","GET"])
def insert():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    if request.method == 'POST':
        fullname = request.form['fullname']
        username = request.form['username']
        email = request.form['email']
        password_hash = request.form['password']
        password = generate_password_hash(password_hash)
        cur.execute("INSERT INTO users (fullname, username, email, password) VALUES (%s,%s,%s,%s)",[fullname,username,email,password])
        conn.commit()       
        cur.close()
    return jsonify('New Records added successfully')
     
if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html>
<head>
<title>Sign Up Form Validation using jqBootstrapValidation using Python Flask Jquery Ajax and PostgreSQL</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqBootstrapValidation/1.3.6/jqBootstrapValidation.js"></script>
<style>
.controls p{
    color:#a94442;
}
</style>
</head>
<body>
<div class="container">
    <h3 align="center">Sign Up Form Validation using jqBootstrapValidation using Python Flask Jquery Ajax and PostgreSQL</h3>
    <br />
    <div class="row">
        <div class="col-md-2"></div>
        <div class="col-md-6">
<form class="form-horizontal" method="POST" id="simple_form" novalidate="novalidate">
  <fieldset>
    <div id="legend">
      <legend class="">Register</legend>
    </div>

    <div class="control-group">
        <label class="control-label"  for="fullname">Name</label>
        <div class="controls">
          <input type="text" id="fullname" name="fullname" class="form-control form-control-lg" placeholder="Name" required="required" data-validation-required-message="Please enter your Name">
          <p class="text-danger help-block"></p>
        </div>
      </div>

    <div class="control-group">
      <label class="control-label"  for="username">Username</label>
      <div class="controls">
        <input type="text" id="username" name="username" class="form-control form-control-lg" placeholder="Name" required="required" data-validation-required-message="Please enter your Username">
        <p class="text-danger help-block"></p>
      </div>
    </div>
  
    <div class="control-group">
      <label class="control-label" for="email">E-mail</label>
      <div class="controls">
        <input type="email" id="email" name="email" class="form-control form-control-lg" placeholder="Email" required="required" data-validation-required-message="Please provide your E-mail">
        <p class="text-danger help-block"></p>
      </div>
    </div>
  
    <div class="control-group">
      <label class="control-label" for="password">Password</label>
      <div class="controls">
        <input type="password" id="password" name="password" class="form-control form-control-lg" placeholder="Password" required="required" data-validation-required-message="Please provide your password">
        <p class="text-danger help-block"></p>
      </div>
    </div>
  
    <div class="control-group">
      <label class="control-label"  for="password_confirm">Password (Confirm)</label>
      <div class="controls">
        <input type="password" id="password_confirm" class="form-control form-control-lg" name="password_confirm" placeholder="Password (Confirm)" required="required" data-validation-required-message="Please confirm password">
        <p class="text-danger help-block"></p>
      </div>
    </div>
  
    <div class="control-group">
        <div id="success"></div>
      <div class="controls">
        <button class="btn btn-success" type="submit" class="form-control form-control-lg" class="btn btn-primary" id="send_button">Register</button>
      </div>
    </div>
  </fieldset>
    </form>
    </div>
    <div class="col-md-2"></div>
</div>
</div>
<script>
$(document).ready(function(){
    $('#simple_form input').jqBootstrapValidation({
        preventSubmit: true,
        submitSuccess: function($form, event){     
            event.preventDefault();
            $this = $('#send_button');
            $this.prop('disabled', true);
            var form_data = $("#simple_form").serialize();
            $.ajax({
               url:"/insert",
               method:"POST",
               data:form_data,
               success:function(){
                $('#success').html("<div class='alert alert-success'><strong>Successfully Register. </strong></div>");
                $('#simple_form').trigger('reset');
               },
               error:function(){
                $('#success').html("<div class='alert alert-danger'>There is some error</div>");
                $('#simple_form').trigger('reset');
               },
               complete:function(){
                setTimeout(function(){
                 $this.prop("disabled", false);
                 $('#success').html('');
                }, 5000);
               }
            });
        },
    });
 
});
</script>
</body>
</html>

Related Post