article

Thursday, January 21, 2021

Python Flask Dynamic Loading of ComboBox using jQuery Ajax and Mysql

Python Flask Dynamic Loading of ComboBox using jQuery Ajax and Mysql

Create Database table
--
-- Table structure for table `carbrands`
--

CREATE TABLE `carbrands` (
  `brand_id` int(11) NOT NULL,
  `brand_name` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `carbrands`
--

INSERT INTO `carbrands` (`brand_id`, `brand_name`) VALUES
(1, 'Toyota'),
(2, 'Honda'),
(3, 'Suzuki'),
(4, 'Mitsubishi'),
(5, 'Hyundai');

--
-- Table structure for table `carmodels`
--

CREATE TABLE `carmodels` (
  `model_id` int(11) NOT NULL,
  `brand_id` int(11) NOT NULL,
  `car_models` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `carmodels`
--

INSERT INTO `carmodels` (`model_id`, `brand_id`, `car_models`) VALUES
(1, 1, 'Toyota Corolla'),
(2, 2, 'Toyota Camry'),
(3, 1, 'Toyota Yaris'),
(4, 1, 'Toyota Sienna'),
(5, 1, 'Toyota RAV4'),
(6, 1, 'Toyota Highlander'),
(7, 2, 'Honda HR-V'),
(8, 2, 'Honda Odyssey'),
(9, 3, 'Swift'),
(10, 3, 'Celerio'),
(11, 3, 'Ertiga'),
(12, 3, 'Vitara'),
(13, 4, 'Mirage'),
(14, 4, 'Mirage G4'),
(15, 4, 'Xpander Cross'),
(16, 4, 'Montero Sport'),
(17, 4, 'Strada Athlete'),
(18, 5, 'Reina '),
(19, 5, 'Accent'),
(20, 5, 'Elantra'),
(21, 5, 'Tucson');

app.py
 
#app.py
from flask import Flask, render_template, request, jsonify
from flask_mysqldb import MySQL,MySQLdb #pip install flask-mysqldb https://github.com/alexferl/flask-mysqldb

app = Flask(__name__)
       
app.secret_key = "caircocoders-ednalan"
       
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'testingdb'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
mysql = MySQL(app)
    
@app.route('/')
def index():
    cursor = mysql.connection.cursor()
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    result = 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 = mysql.connection.cursor(MySQLdb.cursors.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>Python Flask Dynamic Loading of ComboBox using jQuery Ajax and Mysql</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">Python Flask Dynamic Loading of ComboBox using jQuery Ajax and Mysql</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