article

Sunday, June 6, 2021

Display Loading Image when AJAX call is in Progress using Python Flask PostgreSQL

Display Loading Image when AJAX call is in Progress using 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 posts (
id serial PRIMARY KEY,
title VARCHAR ( 100 ) NOT NULL,
content TEXT NOT NULL,
link VARCHAR ( 100 ) NOT NULL,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);


INSERT INTO
    posts(title, content, link, created_at)
VALUES
('What is AngularJS', 'AngularJS is a JavaScript MVC framework  developed by Google that lets you build well structured, easily testable,  declarative and maintainable front-end applications which provides solutions to  standard infrastructure concerns.', 'link-5', '2021-03-20 16:00:00'),
('What is MongoDB', 'It is a quick tutorial on MongoDB and how you can install it on your Windows OS. We will also learn some basic commands in MongoDB for example, creating and dropping a Database, Creation of a collection and some more operations related to the collection.', 'link-6', '2021-03-21 16:00:00'),
('Python Flask Load content Dynamically in Bootstrap Modal with Jquery AJAX and Mysqldb', 'Python Flask Load content Dynamically in Bootstrap Modal with Jquery AJAX and Mysqldb', 'link-6', '2021-03-20 16:00:00'),
('AutoComplete Textbox with Image using jQuery Ajax PHP Mysql and JqueryUI', 'AutoComplete Textbox with Image using jQuery Ajax PHP Mysql and JqueryUI', 'link-7', '2021-03-14 16:00:00'),
('PHP Mysql Registration Form Validation using jqBootstrapValidation with Jquery Ajax', 'PHP Mysql Registration Form Validation using jqBootstrapValidation with Jquery Ajax', 'link-8', '2021-03-20 16:00:00'),
('Python Flask Registration Form Validation using jqBootstrapValidation with Jquery Ajax and Mysql', 'Python Flask Registration Form Validation using jqBootstrapValidation with Jquery Ajax and Mysql', 'link-9', '2021-03-19 16:00:00'),
('Displaying Popups data on mouse hover using Jquery Ajax and PHP Mysql database', 'Displaying Popups data on mouse hover using Jquery Ajax and PHP Mysql database', 'link-10', '2021-03-15 16:00:00'),
('Displaying Popups data on mouse hover using Jquery Ajax and Python Flask Mysql database', 'Displaying Popups data on mouse hover using Jquery Ajax and Python Flask Mysql database', 'link-11', '2021-03-14 16:00:00');

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():
    return render_template('index.html')
 
@app.route("/fetchdeta",methods=["POST","GET"])
def fetchdeta():
    cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    if request.method == 'POST':
        search = request.form['search']
        print(search)
        query = "SELECT * from posts WHERE title LIKE '%{}%'".format(search,)
        cursor.execute(query)
        postslist = cursor.fetchall() 
        cursor.close()
    return jsonify({'htmlresponse': render_template('response.html',postslist=postslist)})
             
if __name__ == "__main__":
    app.run()
templates.index.html
//templates.index.html
<html>
 <head>
  <title>Display Loading Image when AJAX call is in Progress using Python Flask PostgreSQL</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />        
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
 </head>
 <body>
  <div class="container">
  <div class="row">
   <h3 align="center">Display Loading Image when AJAX call is in Progress using Python Flask PostgreSQL</h3>
    Search : 
    <input type='text' id='search' class="form-control" style="width:40%;"><br/>
    <input type='button' id='but_search' value='Search' class="btn btn-default"><br/>
    <!-- Image loader -->
    <div id='loader' style='display: none;'>
      <img src='/static/img/loader.gif'> <b>Loading..</b>
    </div>
    <br/>
    <!-- Image loader -->
    <div class='response'></div>
   </div>
  </div>
<script type='text/javascript'>
 
$(document).ready(function(){
  
 $("#but_search").click(function(){
  var search = $('#search').val();
 
  $.ajax({
   url: '/fetchdeta',
   type: 'post',
   data: {search:search},
   beforeSend: function(){
    // Show image container
    $("#loader").show();
   },
   success: function(response){
    $('.response').empty();
    $('.response').append(response.htmlresponse);
   },
   complete:function(data){
    // Hide image container
    $("#loader").hide();
   }
  });
  
 });
});
</script>
<style>
.post{
    width: 97%;
    min-height: 200px;
    padding: 5px;
    border: 1px solid gray;
    margin-bottom: 15px;
}
.post h1{
    letter-spacing: 1px;
    font-weight: normal;
    font-family: sans-serif;
}
.post p{
    letter-spacing: 1px;
    text-overflow: ellipsis;
    line-height: 25px;
}
</style>
 </body>
</html>
templates/response.html
//templates/response.html
{% for row in postslist %}
<div class="post" id="post_{{row.id}}">
<h1>{{row.title}}</h1>
<p>{{row.content}}</p>
<a href="{{row.link}}" class="more" target="_blank">More</a>
</div>
{% endfor %}

Related Post