article

Friday, June 4, 2021

Filter Records using jQuery UI slider with Jquery Ajax and Python Flask PostgreSQL

Filter Records using jQuery UI slider with Jquery Ajax and 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

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');

JqueryUI Slider https://jqueryui.com/slider/
app.py
 
#app.py
from flask import Flask, request, render_template, jsonify, json
import psycopg2 #pip install psycopg2 
import psycopg2.extras
   
app = Flask(__name__)
   
app.secret_key = "cairocoders-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 home():
    try:
        cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
        cursor.execute("SELECT * from employee order by name asc")
        employeelist = cursor.fetchall()
        return render_template('index.html',employeelist=employeelist)
    except Exception as e:
        print(e)
    finally:
        cursor.close() 
 
@app.route("/fetchdeta",methods=["POST","GET"])
def fetchdeta():
    try:
        cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
        if request.method == 'POST':
            min = request.form['min']
            max = request.form['max']
            cursor.execute("SELECT * from employee WHERE salary>=(%s) AND salary<=(%s)", [min,max,])
            employeelist = cursor.fetchall()
            return jsonify({'htmlresponse': render_template('response.html',employeelist=employeelist)})
    except Exception as e:
        print(e)
    finally:
        cursor.close() 
 
if __name__ == "__main__":
    app.run()
templates/index.html
//templates/index.html
<!doctype html>
<html>
<head>
<title>Filter Records using jQuery UI slider with Jquery Ajax and Python Flask PostgreSQL</title>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type='text/javascript'>
        $(document).ready(function(){
 
            // Initializing slider
            $( "#slider" ).slider({
                range: true,
                min: 100,
                max: 360000,
                values: [ 100, 360000 ],
                slide: function( event, ui ) {
                    // Get values
                    var min = ui.values[0];
                    var max = ui.values[1];
                    $('#range').text(min+' - ' + max);
 
                    // AJAX request
                    $.ajax({
                        url: '/fetchdeta',
                        type: 'post',
                        data: {min:min,max:max},
                        success: function(response){
 
                            // Updating table data
                            $('#emp_table tr:not(:first)').remove();
                            $('#emp_table').append(response.htmlresponse);    
                        }      
                    });
                }
            });
        });
        </script>
    </head>
    <body >
        <div class="container" >
        <div class="row" style="padding:50px;">
            <p><h1>Filter Records using jQuery UI slider with Jquery Ajax and Python Flask PostgreSQL</h1></p>
            <!-- slider --> 
            <div id="slider"></div><br/>
            Range: <span id='range'></span>
 
            <table id='emp_table' class="alternate" width='100%'>
                <tr>
                    <th>Name</th>
                    <th>Position</th>
                    <th>Office</th>
                    <th>Salary</th>
                    </tr>
                    {% for row in employeelist %}  
                    <tr>
                      <td>{{row.name}}</td>
                      <td>{{row.position}}</td>
                      <td>{{row.office}}</td>
                      <td>{{row.salary}}</td>
                    </tr>
                    {% endfor %} 
            </table>
        </div>
        </div>
<style>
.alternate tr:nth-child(2n) {
  background-color: silver;
}
.alternate tr {
  background-color: white;
}
.alternate tr td {padding: 8px;}
.alternate tr:nth-child(2n):hover, .alternate tr:hover {
  background-color: grey;
}
</style>  
</body>
</html>
templates/response.html
//templates/response.html
{% for row in employeelist %}
<tr>
    <td>{{row.name}}</td>
    <td>{{row.position}}</td>
    <td>{{row.office}}</td>
    <td>{{row.salary}}</td>
</tr>
{% endfor %} 

Related Post