article

Sunday, July 4, 2021

Dynamic Drag and Drop Order List With jQuery Ajax and Python Flask PostgreSQL Database

Dynamic Drag and Drop Order List With jQuery Ajax and Python Flask PostgreSQL Database

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 dragdrop (
id serial PRIMARY KEY,
text VARCHAR ( 150 ) NOT NULL,
listorder INT NOT NULL
);

INSERT INTO
    dragdrop(text,listorder)
VALUES
('Ajax', 3),
('Jquery', 5),
('PHP', 6),
('Mysqli', 7),
('Javascript', 1),
('Java', 4),
('Python', 2);

jqueryui sortable https://jqueryui.com/sortable/
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 dragdrop ORDER BY listorder ASC")
    dragdrop = cur.fetchall() 
    return render_template('index.html', dragdrop=dragdrop)
 
@app.route("/updateList",methods=["POST","GET"])
def updateList():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    if request.method == 'POST':
        cur.execute("SELECT * FROM dragdrop")    
        number_of_rows = cur.rowcount      
        getorder = request.form['order']    
        print(getorder)
        order = getorder.split(",", number_of_rows)
        print(order)
        count=0   
        for value in order:
            count +=1
            print(count)                       
            cur.execute("UPDATE dragdrop SET listorder = %s WHERE id = %s ", [count, value])
            conn.commit()       
        cur.close()
    return jsonify('Successfully Updated')
 
if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dynamic Drag and Drop Order List With jQuery Ajax and Python Flask PostgreSQL Database</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript">
$(document).ready(function(){  
   function slideout(){
    setTimeout(function(){
      $("#response").slideUp("slow", function () {
    });
    }, 2000);
  }
   
  $("#response").hide();
  $(function() {
    $("#list ul").sortable({ opacity: 0.8, cursor: 'move', update: function() {
      var item_order = new Array();
      $('ul.reorder li').each(function() {
          item_order.push($(this).attr("id"));
      }); 
      var order_string = 'order='+item_order;
      $.ajax({
        method: "POST",
        url: "/updateList",
        data: order_string,
        cache: false,
        success: function(data){    
            $("#response").html(data);
            $("#response").slideDown('slow');
            slideout();
        }
    });               
    }         
    });
   });
  
}); 
</script>
</head>
<body>
<center>  
<p><h1>Dynamic Drag and Drop Order List With jQuery Ajax and Python Flask PostgreSQL Database</h1></p>
<div style="width:300px;">
  <div id="list">
  <div id="response"> </div>
      <ul class="reorder">
        {% for row in dragdrop %}
        <li id="{{row.id}}">{{row.text}}
          <div class="clear"></div>
        </li>
        {% endfor %}
      </ul>
  </div>
</div>
</center>

<style>
ul {
 padding:0px;
 margin: 0px;
}
#response {
 padding:10px;
 background-color:#9F9;
 border:2px solid #396;
 margin-bottom:20px;
}
#list li {
 margin: 0 0 3px;
 padding:8px;text-align:left;
 background-color:#00CCCC;
 color:#fff;
 list-style: none;
 border: #CCCCCC solid 1px;
}
</style>
</body>
</html>

Related Post