article

Monday, February 15, 2021

Python Flask Jquery Ajax Live Data Search Select Dropdown

Python Flask Jquery Ajax Live Data Search Select Dropdown

--
-- Table structure for table `employee`
--

CREATE TABLE `employee` (
  `id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `position` varchar(100) NOT NULL,
  `office` varchar(100) NOT NULL,
  `age` int(11) NOT NULL,
  `salary` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `employee`
--

INSERT INTO `employee` (`id`, `name`, `position`, `office`, `age`, `salary`) VALUES
(1, 'Caite Ednalan', 'Accountant', 'Tokyo', 36, 5689),
(2, 'Mark Oto Ednalan', 'Chief Executive Officer (CEO)', 'London', 56, 5648),
(3, 'Jacob thompson', 'Junior Technical Author', 'San Francisco', 23, 5689),
(4, 'cylde Ednalan', 'Software Engineer', 'Olongapo', 23, 54654),
(5, 'Angelica Ramos', 'Software Engineer', 'San Francisco', 26, 5465),
(6, 'Airi Satou', 'Integration Specialist', 'New York', 53, 56465),
(8, 'Tiger Nixon', 'Software Engineer', 'London', 45, 456),
(9, 'Airi Satou', 'Pre-Sales Support', 'New York', 25, 4568),
(10, 'Angelica Ramos', 'Sales Assistant', 'New York', 45, 456),
(11, 'Ashton updated', 'Senior Javascript Developer', 'Olongapo', 45, 54565),
(12, 'Bradley Greer', 'Regional Director', 'San Francisco', 27, 5485),
(13, 'Brenden Wagner', 'Javascript Developer', 'San Francisco', 38, 65468),
(14, 'Brielle Williamson', 'Personnel Lead', 'Olongapo', 56, 354685),
(15, 'Bruno Nash', 'Customer Support', 'New York', 36, 65465),
(16, 'cairocoders', 'Sales Assistant', 'Sydney', 45, 56465),
(17, 'Zorita Serrano', 'Support Engineer', 'San Francisco', 38, 6548),
(18, 'Zenaida Frank', 'Chief Operating Officer (COO)', 'San Francisco', 39, 545),
(19, 'Yuri Berry', 'Accountant', 'Tokyo', 38, 5468);

--
-- Indexes for dumped tables
--

--
-- Indexes for table `employee`
--
ALTER TABLE `employee`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `employee`
--
ALTER TABLE `employee`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=20;
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():
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    cur.execute("SELECT DISTINCT office FROM employee ORDER BY office ASC")
    employee = cur.fetchall()  
    return render_template('index.html', employee = employee)

@app.route("/fetchrecords",methods=["POST","GET"])
def fetchrecords():
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    if request.method == 'POST':
        query = request.form['query']
        #print(query)
        if query == '':
            cur.execute("SELECT * FROM employee ORDER BY id DESC")
            employeelist = cur.fetchall()
            print('all list')
        else:
            search_text = request.form['query']
            print(search_text)
            cur.execute("SELECT * FROM employee WHERE office IN (%s) ORDER BY id DESC", [search_text])
            employeelist = cur.fetchall()  
    return jsonify({'htmlresponse': render_template('response.html', employeelist=employeelist)})

if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<title>Python Flask Jquery Ajax Live Data Search Select Dropdown</title>
		<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
		<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
		<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
	</head>
	<body>
		<div class="container">
			<br />
			<h2 align="center">Python Flask Jquery Ajax Live Data Search Select Dropdown</h2><br />
			<select name="search_filter" id="search_filter" class="form-control">
			<option value="">Select Option</option>';
			{% for row in employee %}
				<option value="{{row.office}}">{{row.office}}</option>';	
			{% endfor %}
			</select>
			<input type="hidden" name="hidden_value" id="hidden_value" />
			<div style="clear:both"></div>
			<br />
			<div class="table-responsive">
				<table class="table table-striped table-bordered">
					<thead>
						<tr>
							<th>Name</th>
							<th>Position</th>
							<th>Age</th>
							<th>Salary</th>
							<th>Office</th>
						</tr>
					</thead>
					<tbody>
					</tbody>
				</table>
			</div>
			<br />
			<br />
			<br />
		</div>
<script>
$(document).ready(function(){
	load_data();
	function load_data(query='')
	{
		$.ajax({
			url:"/fetchrecords",
			method:"POST",
			data:{query:query},
			success:function(data)
			{ 
				$('tbody').html(data);
				$('tbody').append(data.htmlresponse);
			}
		})
	}

	$('#search_filter').change(function(){
		$('#hidden_value').val($('#search_filter').val());
		var query = $('#hidden_value').val(); 
		load_data(query);
	});
	
});
</script>
</body>
</html>
templates/response.html
//templates/response.html
{% for row in employeelist %}  
<tr>
    <td>{{row.name}}</td>
    <td>{{row.position}}</td>
    <td>{{row.age}}</td>
    <td>{{ "$%.2f"|format(row.salary) }}</td>
    <td>{{row.office}}</td>
</tr>
{% endfor %} 

Related Post