Load content Dynamically in Bootstrap Modal with Jquery AJAX and Python Flask PostgreSQL

Subscribe: https://www.youtube.com/c/Cairocoders/featured

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

Source Code

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")
    employee = cur.fetchall()  
    return render_template('index.html', employee = employee)
  
@app.route("/ajaxfile",methods=["POST","GET"])
def ajaxfile():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    if request.method == 'POST':
        userid = request.form['userid']
        print(userid)
        cur.execute("SELECT * FROM employee WHERE id = %s", [userid])
        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
<!DOCTYPE html>
<html>
<head>
<title>Load content Dynamically in Bootstrap Modal with Jquery AJAX and 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>
</head>
<body >
<div class="container">
   <br />
   <h3 align="center">Load content Dynamically in Bootstrap Modal with Jquery AJAX and Python Flask PostgreSQL</h3>
   <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>
                            <th>View</th>
                        </tr>
                        </thead> 
                        {% for row in employee %}
                            <tr>
                                <td><img src="/static/images/{{row.photo}}" height="50" width="50"/></td>
                                <td>{{row.name}}</td>
                                <td>{{row.position}}</td>
                                <td>{{row.office}}</td>
                                <td>{{row.age}}</td>
                                <td>{{row.salary}}</td>
                                <td><button data-id='{{row.id}}' class="userinfo btn btn-success">Info</button></td>
                            </tr>
                        {% endfor %}
                </table>
            </div>
        </div>    
    </div>    
    </div>
</div>    
            <script type='text/javascript'>
            $(document).ready(function(){
                $('.userinfo').click(function(){
                    var userid = $(this).data('id');
                    $.ajax({
                        url: '/ajaxfile',
                        type: 'post',
                        data: {userid: userid},
                        success: function(data){ 
                            $('.modal-body').html(data); 
                            $('.modal-body').append(data.htmlresponse);
                            $('#empModal').modal('show'); 
                        }
                    });
                });
            });
            </script>
        </div>
        <div class="modal fade" id="empModal" role="dialog">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h4 class="modal-title">User Info</h4>
                          <button type="button" class="close" data-dismiss="modal">×</button>
                        </div>
                        <div class="modal-body">
                        </div>
                        <div class="modal-footer">
                          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                        </div>
                    </div>
                </div>
        </div>
    </body>
</html>


templates/response.html


//templates/response.html
{% for row in employeelist %} 
<table border='0' width='100%'>
    <tr>
        <td width="300"><img src="/static/images/{{row.photo}}">
        <td style="padding:20px;">
        <p>Name : {{row.name}}</p>
        <p>Position : {{row.position}}</p>
        <p>Office : {{row.office}}</p>
        <p>Age : {{row.age}}</p>
        <p>Salary : {{row.salary}}</p>
        </td>
    </tr>
</table>
{% endfor %}

#python #postgresql #flask

Load content Dynamically in Bootstrap Modal with Jquery AJAX and Python Flask PostgreSQL
11.30 GEEK