How to Table Edit using jquery ajax Python Flask and PostgreSQL Database

How to Table Edit using jquery ajax Python Flask and PostgreSQL Database

Learn how to Table Edit using jquery ajax Python Flask and PostgreSQL Database

Learn how to Table Edit using jquery ajax Python Flask and PostgreSQL Database

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

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 programming ORDER BY id ASC")
    topphpframework = cur.fetchall() 
    return render_template('index.html', topphpframework=topphpframework)

@app.route("/ajax",methods=["POST","GET"])
def ajax():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)    
    if request.method == 'POST':
        getid = request.form['id']
        getname = request.form['name']
        print(getid)
        cur.execute("UPDATE programming SET title = %s WHERE id = %s ", [getname, getid])
        conn.commit()       
        cur.close()
    return jsonify('Record updated successfully')

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>Table Edit using jquery ajax Python Flask and PostgreSQL Database</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
  $(".edit_tr").click(function() {
    var ID=$(this).attr('id');
    $("#first_"+ID).hide();
    $("#first_input_"+ID).show();
  }).change(function(){
      var ID=$(this).attr('id');
      var first=$("#first_input_"+ID).val();
      var dataString = 'id='+ ID +'&name='+first;
      $("#first_"+ID).html('<img src="/staticf/img/loader.gif" />');
      if(first.length>0){
        $.ajax({
          type: "POST",
          url: "/ajax",
          data: dataString,
          cache: false,
          success: function(html)
          {
            $("#first_"+ID).html(first);
          }
        });
      }else{
        alert('Enter something.');
      }
  });

  $(".editbox").mouseup(function() {
   return false
  });
  $(document).mouseup(function() {
      $(".editbox").hide();
      $(".text").show();
  });
});
</script>
</head>
<body>
<center><p><h1>Table Edit using jquery ajax Python Flask and PostgreSQL Database</h1></p></center>
<div style="margin:0 auto; width:350px; padding:10px; background-color:#fff;"> 
<table width="100%" border="0">
  <tr class="head">
  <th>Frameworks</th>
  </tr>
  {% for row in topphpframework %}
      <tr id="{{row.id}}" bgcolor="#f2f2f2" class="edit_tr">
        <td width="50%" class="edit_td">
        <span id="first_{{row.id}}" class="text">{{row.title}}</span>
        <input type="text" name="name" value="{{row.title}}" class="editbox" id="first_input_{{row.id}}" />
        </td>
      </tr>
    {% endfor %}
</table>
</div>
<style>
  body
  {
  font-family:Arial, Helvetica, sans-serif;
  font-size:16px;
  }
  .head
  {
  background-color:#333;
  color:#FFFFFF
  }
  .edit_tr:hover
  {
  background:url(/static/img/edit.png) right no-repeat #80C8E5;
  cursor:pointer;
  }
  .editbox
  {
  display:none
  }
  .editbox
  {
  font-size:16px;
  width:270px;
  background-color:#ffffcc;
  border:solid 1px #000;
  padding:4px;
  }
  td
  {
  padding:10px;
  }
  th
  {
  font-weight:bold;
  text-align:left;
  padding:4px;
  }
  </style>
</body>
</html>

python postgresql

What is Geek Coin

What is GeekCash, Geek Token

Best Visual Studio Code Themes of 2021

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

top 30 Python Tips and Tricks for Beginners

In this post, we'll learn top 30 Python Tips and Tricks for Beginners

Lambda, Map, Filter functions in python

You can learn how to use Lambda,Map,Filter function in python with Advance code examples. Please read this article

Python Tricks Every Developer Should Know

In this tutorial, you’re going to learn a variety of Python tricks that you can use to write your Python code in a more readable and efficient way like a pro.

How to Remove all Duplicate Files on your Drive via Python

Today you're going to learn how to use Python programming in a way that can ultimately save a lot of space on your drive by removing all the duplicates. We gonna use Python OS remove( ) method to remove the duplicates on our drive. Well, that's simple you just call remove ( ) with a parameter of the name of the file you wanna remove done.

Basic Data Types in Python | Python Web Development For Beginners

In the programming world, Data types play an important role. Each Variable is stored in different data types and responsible for various functions. Python had two different objects, and They are mutable and immutable objects.