article

Monday, July 5, 2021

Dynamic Loading of ComboBox using jQuery Ajax Python Flask and PostgreSQL



Dynamic Loading of ComboBox 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

INSERT INTO
    carbrands(brand_name)
VALUES
('Toyota'),
('Honda'),
('Suzuki'),
('Mitsubishi'),
('Hyundai');

CREATE TABLE carmodels (
model_id serial PRIMARY KEY,
brand_id INT NOT NULL,
car_models VARCHAR ( 150 ) NOT NULL
);

INSERT INTO
    carmodels(brand_id,car_models)
VALUES
(1, 'Toyota Corolla'),
(2, 'Toyota Camry'),
(1, 'Toyota Yaris'),
(1, 'Toyota Sienna'),
(1, 'Toyota RAV4'),
(1, 'Toyota Highlander'),
(2, 'Honda HR-V'),
(2, 'Honda Odyssey'),
(3, 'Swift'),
(3, 'Celerio'),
(3, 'Ertiga'),
(3, 'Vitara'),
(4, 'Mirage'),
(4, 'Mirage G4'),
(4, 'Xpander Cross'),
(4, 'Montero Sport'),
(4, 'Strada Athlete'),
(5, 'Reina '),
(5, 'Accent'),
(5, 'Elantra'),
(5, 'Tucson');
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 carbrands ORDER BY brand_id")
    carbrands = cur.fetchall() 
    return render_template('index.html', carbrands=carbrands)
 
@app.route("/get_child_categories",methods=["POST","GET"])
def get_child_categories():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)    
    if request.method == 'POST':
        parent_id = request.form['parent_id']
        print(parent_id)
        cur.execute("SELECT * FROM carmodels WHERE brand_id = %s", [parent_id])
        carmodels = cur.fetchall()
    return jsonify({'htmlresponse': render_template('response.html', carmodels=carmodels)})

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>Dynamic Loading of ComboBox using jQuery Ajax Python Flask and PostgreSQL</title>
<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.6/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
 $('#search_category_id').change(function(){
    $.post("/get_child_categories", {
     parent_id: $('#search_category_id').val(),
    }, function(response){ 
        $('#show_sub_categories').html(response);
        $('#show_sub_categories').append(response.htmlresponse);
    });
    return false;
  });
}); 
</script>
</head>
<body>
  <div class="container">
    <div class="row">
      <div class="col-lg-2"></div>
    <div class="col-lg-8">
    <h3 align="center">Dynamic Loading of ComboBox using jQuery Ajax Python Flask and PostgreSQL</h3>
    <form action="#" name="form" id="form" method="post">
      <div class="form-group">
        <label>Select Category</label>
        <select name="search_category"  id="search_category_id" class="form-control">
          <option value="" selected="selected"></option>
          {% for row in carbrands %}
          <option value='{{row.brand_id}}'>{{row.brand_name}}</option>
          {% endfor %}
          </select> 
      </div>
      <div id="show_sub_categories"></div>
      <button type="submit" class="btn btn-primary">Submit</button>
    </form>
    </div>
    <div class="col-lg-2"></div>
  </div>
</div>
</body>
</html>
templates/response.html
//templates/response.html
<div class="form-group">
    <label>Select Sub Category</label>
    <select name="sub_category"  id="sub_category_id" class="form-control">
       <option value="" selected="selected"></option>
        {% for row in carmodels %} 
        <option value="{{row.model_id}}">{{row.car_models}}</option>
        {% endfor %}
    </select> 
</div>

Related Post