article

Friday, January 15, 2021

Python Flask add edit delete Datatable Row Using Jquery Ajax and mysqldb database


Python Flask add edit delete Datatable Row Using Jquery Ajax and mysqldb database

#app.py
from flask import Flask, render_template, redirect, request, flash, 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)
    result = cur.execute("SELECT * FROM tblemployee ORDER BY id")
    employee = cur.fetchall()
    return render_template('index.html', employee=employee)

@app.route("/ajax_add",methods=["POST","GET"])
def ajax_add():
    cursor = mysql.connection.cursor()
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    if request.method == 'POST':
        txtname = request.form['txtname']
        txtdepartment = request.form['txtdepartment']
        txtphone = request.form['txtphone']
        print(txtname)
        if txtname == '':
            msg = 'Please Input name'   
        elif txtdepartment == '':
           msg = 'Please Input Department'   
        elif txtphone == '':
           msg = 'Please Input Phone'   
        else:        
            cur.execute("INSERT INTO tblemployee (name,department,phone) VALUES (%s,%s,%s)",[txtname,txtdepartment,txtphone])
            mysql.connection.commit()       
            cur.close()
            msg = 'New record created successfully'    
    return jsonify(msg)

@app.route("/ajax_update",methods=["POST","GET"])
def ajax_update():
    cursor = mysql.connection.cursor()
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    if request.method == 'POST':
        string = request.form['string']
        txtname = request.form['txtname']
        txtdepartment = request.form['txtdepartment']
        txtphone = request.form['txtphone']
        print(string)
        cur.execute("UPDATE tblemployee SET name = %s, department = %s, phone = %s WHERE id = %s ", [txtname, txtdepartment, txtphone, string])
        mysql.connection.commit()       
        cur.close()
        msg = 'Record successfully Updated'    
    return jsonify(msg)    

@app.route("/ajax_delete",methods=["POST","GET"])
def ajax_delete():
    cursor = mysql.connection.cursor()
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    if request.method == 'POST':
        getid = request.form['string']
        print(getid)
        cur.execute('DELETE FROM tblemployee WHERE id = {0}'.format(getid))
        mysql.connection.commit()       
        cur.close()
        msg = 'Record deleted successfully'    
    return jsonify(msg) 

    
if __name__ == "__main__":
    app.run(debug=True)
index.html
//index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Python Flask add edit delete Row Using Jquery Ajax and mysqldb database</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style type="text/css">
    body {
        color: #404E67;
        background: #F5F7FA;
  font-family: 'Open Sans', sans-serif;
 }
 .table-wrapper {
  width: 700px;
  margin: 30px auto;
        background: #fff;
        padding: 20px; 
        box-shadow: 0 1px 1px rgba(0,0,0,.05);
    }
    .table-title {
        padding-bottom: 10px;
        margin: 0 0 10px;
    }
    .table-title h2 {
        margin: 6px 0 0;
        font-size: 22px;
    }
    .table-title .add-new {
        float: right;
  height: 30px;
  font-weight: bold;
  font-size: 12px;
  text-shadow: none;
  min-width: 100px;
  border-radius: 50px;
  line-height: 13px;
    }
 .table-title .add-new i {
  margin-right: 4px;
 }
    table.table {
        table-layout: fixed;
    }
    table.table tr th, table.table tr td {
        border-color: #e9e9e9;
    }
    table.table th i {
        font-size: 13px;
        margin: 0 5px;
        cursor: pointer;
    }
    table.table th:last-child {
        width: 100px;
    }
    table.table td a {
  cursor: pointer;
        display: inline-block;
        margin: 0 5px;
  min-width: 24px;
    }   
 table.table td a.add {
        color: #27C46B;
    }
    table.table td a.edit {
        color: #FFC107;
    }
    table.table td a.delete {
        color: #E34724;
    }
    table.table td i {
        font-size: 19px;
    }
 table.table td a.add i {
        font-size: 24px;
     margin-right: -1px;
        position: relative;
        top: 3px;
    }    
    table.table .form-control {
        height: 32px;
        line-height: 32px;
        box-shadow: none;
        border-radius: 2px;
    }
 table.table .form-control.error {
  border-color: #f50000;
 }
 table.table td .add {
  display: none;
 }
</style>
<script type="text/javascript">
$(document).ready(function(){
    $('[data-toggle="tooltip"]').tooltip();
    var actions = $("table td:last-child").html();
    // Append table with add row form on add new button click
    $(".add-new").click(function(){
        $(this).attr("disabled", "disabled");
        var index = $("table tbody tr:last-child").index();
        var row = '<tr>' +
            '<td><input type="text" class="form-control" name="name" id="txtname"></td>' +
            '<td><input type="text" class="form-control" name="department" id="txtdepartment"></td>' +
            '<td><input type="text" class="form-control" name="phone" id="txtphone"></td>' +
        '<td>' + actions + '</td>' +
        '</tr>';
        $("table").append(row);  
        $("table tbody tr").eq(index + 1).find(".add, .edit, .delete").toggle();
        $('[data-toggle="tooltip"]').tooltip();

    });
  
    // Add row on add button click
    $(document).on("click", ".add", function(){
        var empty = false;
        var input = $(this).parents("tr").find('input[type="text"]');
        input.each(function(){
            if(!$(this).val()){
                $(this).addClass("error");
                empty = true;
            } else{
                $(this).removeClass("error");
            }
        });
        var txtname = $("#txtname").val();
        var txtdepartment = $("#txtdepartment").val();
        var txtphone = $("#txtphone").val();
        $.post("/ajax_add", { txtname: txtname, txtdepartment: txtdepartment, txtphone: txtphone}, function(data) {
            $("#displaymessage").html(data);
            $("#displaymessage").show();
        });
        $(this).parents("tr").find(".error").first().focus();
        if(!empty){
            input.each(function(){
                $(this).parent("td").html($(this).val());
            });   
            $(this).parents("tr").find(".add, .edit").toggle();
            $(".add-new").removeAttr("disabled");
        } 
    });
    // Delete row on delete button click
    $(document).on("click", ".delete", function(){
        $(this).parents("tr").remove();
        $(".add-new").removeAttr("disabled");
        var id = $(this).attr("id");
        var string = id;
        $.post("/ajax_delete", { string: string}, function(data) {
            $("#displaymessage").html(data);
            $("#displaymessage").show();
        });
    });
    // update rec row on edit button click
    $(document).on("click", ".update", function(){
        var id = $(this).attr("id");
        var string = id;
        var txtname = $("#txtname").val();
        var txtdepartment = $("#txtdepartment").val();
        var txtphone = $("#txtphone").val();
        $.post("/ajax_update", { string: string,txtname: txtname, txtdepartment: txtdepartment, txtphone: txtphone}, function(data) {
            $("#displaymessage").html(data);
            $("#displaymessage").show();
        });
        
        
    });
    // Edit row on edit button click
    $(document).on("click", ".edit", function(){  
        $(this).parents("tr").find("td:not(:last-child)").each(function(i){
            if (i=='0'){
                var idname = 'txtname';
            }else if (i=='1'){
                var idname = 'txtdepartment';
            }else if (i=='2'){
                var idname = 'txtphone';
            }else{} 
            $(this).html('<input type="text" name="updaterec" id="' + idname + '" class="form-control" value="' + $(this).text() + '">');
        });  
        $(this).parents("tr").find(".add, .edit").toggle();
        $(".add-new").attr("disabled", "disabled");
        $(this).parents("tr").find(".add").removeClass("add").addClass("update"); 
    });
});
</script> 
</head>
<body>
    <div class="container"><p><h1 align="center">Python Flask add edit delete Datatable Row Using Jquery Ajax and mysqldb database</h1></p>
        <div class="table-wrapper">
            <div class="table-title">
                <div class="row">
                    <div class="col-sm-8"><h2>Employee <b>Details</b></h2></div>
                    <div class="col-sm-4">
                        <button type="button" class="btn btn-info add-new"><i class="fa fa-plus"></i> Add New</button>
                    </div>
                    <div class='btn btn-info' id="displaymessage" style="display:none;width:100%;margin-top:10px;"></div>
                </div>
            </div>
   <table class="table table-bordered">
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Department</th>
                        <th>Phone</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    {% for row in employee %}    
                    <tr>
                        <td>{{row.name}}</td>
                        <td>{{row.department}}</td>
                        <td>{{row.phone}}</td>
                        <td>
                            <a class="add" title="Add" data-toggle="tooltip" id="{{row.id}}"><i class="fa fa-user-plus"></i></a>
                            <a class="edit" title="Edit" data-toggle="tooltip" id="{{row.id}}"><i class="fa fa-pencil"></i></a>
                            <a class="delete" title="Delete" data-toggle="tooltip" id="{{row.id}}"><i class="fa fa-trash-o"></i></a>
                        </td>
                    </tr>   
                    {% endfor %}    
                </tbody>
            </table>
        </div>
    </div>     
</body>
</html> 

Wednesday, January 13, 2021

Python Flask Upload Multiple Images and insert to database using mysqldb


Python Flask Upload Multiple Images and insert to database using mysqldb

Create Database Table

CREATE TABLE `images` (
  `id` int(11) NOT NULL,
  `file_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `uploaded_on` datetime NOT NULL,
  `status` enum('1','0') COLLATE utf8_unicode_ci NOT NULL DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
app.py
 
#app.py
from flask import Flask, render_template, redirect, request, flash
from flask_mysqldb import MySQL,MySQLdb #pip install flask-mysqldb https://github.com/alexferl/flask-mysqldb
from werkzeug.utils import secure_filename
import os
#import magic
import urllib.request
from datetime import datetime

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)

UPLOAD_FOLDER = 'static/uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
 
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
 
def allowed_file(filename):
 return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/',methods=["POST","GET"])
def index():
    return render_template('index.html')

@app.route("/upload",methods=["POST","GET"])
def upload():
    cursor = mysql.connection.cursor()
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    now = datetime.now()
    if request.method == 'POST':
        files = request.files.getlist('files[]')
        #print(files)
        for file in files:
            if file and allowed_file(file.filename):
                filename = secure_filename(file.filename)
                file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
                cur.execute("INSERT INTO images (file_name, uploaded_on) VALUES (%s, %s)",[filename, now])
                mysql.connection.commit()
            print(file)
        cur.close()   
        flash('File(s) successfully uploaded')    
    return redirect('/')

if __name__ == "__main__":
    app.run(debug=True)
index.html
//index.html
<!DOCTYPE html>
<html>
<head>
 <title>Python Flask Upload Multiple Images and insert to database using mysqldb</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<h2>Python Flask Upload Multiple Images and insert to database using mysqldb</h2>
    <div class="row">
        <div class="col-lg-12">
            <p>
                {% with messages = get_flashed_messages() %}
                  {% if messages %}
                 {% for message in messages %}
                   <div class="alert alert-success">
                    <strong>{{ message }}</strong>
                  </div>
                 {% endfor %}
                  {% endif %}
                {% endwith %}
               </p>
  <div>
   <!-- File upload form -->
   <form method="post" action="/upload" enctype="multipart/form-data" class="form-inline">
    <div class="form-group">
                      <label>Choose Images: </label>
                      <input type="file" name="files[]" id="fileInput" class="form-control" multiple >
                 </div>
                 <input type="submit" name="submit" class="btn btn-success" value="UPLOAD"/>
             </form>
  </div>
  </div>
 </div>
</div>
<script>
$(document).ready(function(){
 // File type validation
    $("#fileInput").change(function(){
        var fileLength = this.files.length;
        var match= ["image/jpeg","image/png","image/jpg","image/gif"];
        var i;
        for(i = 0; i < fileLength; i++){ 
            var file = this.files[i];
            var imagefile = file.type;
            if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2]) || (imagefile==match[3]))){
                alert('Please select a valid image file (JPEG/JPG/PNG/GIF).');
                $("#fileInput").val('');
                return false;
            }
        }
    });
});
</script>
</body>
</html>

Python Flask Add Remove Input Fields Dynamically with JQuery Ajax and Mysqldb

Python Flask Add Remove Input Fields Dynamically with JQuery Ajax and Mysqldb


app.py
#app.py
from flask import Flask, render_template, jsonify, request
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():
    return render_template('index.html')

@app.route("/postskill",methods=["POST","GET"])
def postskill():
    cursor = mysql.connection.cursor()
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    if request.method == 'POST':
        skills = request.form.getlist('skill[]')
        for value in skills:  
            cur.execute("INSERT INTO skills (skillname) VALUES (%s)",[value])
            mysql.connection.commit()       
        cur.close()
        msg = 'New record created successfully'     
    return jsonify(msg)

if __name__ == "__main__":
    app.run(debug=True)
index.html
//index.html
<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Python Flask Add Remove Input Fields Dynamically with JQuery Ajax and Mysqldb</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>    
</head>
<body>
 <script>
$(document).ready(function() {
 
var MaxInputs       = 8; //maximum input boxes allowed
var InputsWrapper   = $("#InputsWrapper"); //Input boxes wrapper ID
var AddButton       = $("#AddMoreFileBox"); //Add button ID
 
var x = InputsWrapper.length; //initlal text box count
var FieldCount=1; //to keep track of text box added
 
$(AddButton).click(function (e)  //on add input button click
{
        if(x <= MaxInputs) //max input box allowed
        {
            FieldCount++; //text box added increment
            //add input box
            $(InputsWrapper).append('<div class="row"><p class="col-xs-6"><input type="text" placeholder="Enter your skill" class="form-control skill_list" name="skill[]" id="field_'+ FieldCount +'" value="Enter your skill '+ FieldCount +'"/></p><a href="#" class="btn btn-danger removeclass">×</a></div>');
            x++; //text box increment
        }
return false;
});
 
$("body").on("click",".removeclass", function(e){ //user click on remove text
        if( x > 1 ) {
                $(this).parent('div').remove(); //remove text box
                x--; //decrement textbox
        }
return false;
})
 $('#submit').click(function(){            
           $.ajax({  
                url:"/postskill",  
                method:"POST",  
                data:$('#add_skills').serialize(),  
                success:function(data)  
                {  alert(data)
                     $('#resultbox').html(data);  
                     $('#add_skills')[0].reset();  
                }  
           });  
      }); 
});
</script>
<style>
.row {padding:10px;}
</style>
<div class="container">  
                <br />  
                <br />  
                <h2 align="center">Python Flask Add Remove Input Fields Dynamically with JQuery Ajax and Mysqldb</h2><div id="resultbox"></div>  
                <div class="form-group">  
                     <form name="add_skills" id="add_skills">  
                                    <div id="InputsWrapper">
          <div class="row">
                                         <div class="col-xs-6"><input type="text" name="skill[]" placeholder="Enter your skill" class="form-control name_list" /></div>
                                         <div class="col-xs-6"><button type="button" name="add" id="AddMoreFileBox" class="btn btn-success">Add More</button></div>
           </div>
         </div>
         <br/>
                               <input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />  
                     </form>  
                </div>  
           </div>  
</body>
</html>

Tuesday, January 12, 2021

Python Flask Create a Progress Bar Data Insert using Jquery Ajax Bootstrap and Mysqldb database

Python Flask Create a Progress Bar Data Insert using Jquery Ajax Bootstrap and Mysqldb database


app.py
 
#app.py
from flask import Flask, render_template, jsonify, request
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():
    return render_template('index.html')
 
@app.route("/ajaxprogressbar",methods=["POST","GET"])
def ajaxprogressbar():
    if request.method == 'POST':
        username = request.form['username']
        useremail = request.form['useremail']
        print(username)
        cursor = mysql.connection.cursor()
        cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        cur.execute("INSERT INTO tbl_user (username, useremail) VALUES (%s, %s)",[username, useremail])
        mysql.connection.commit()
        cur.close()
        msg = 'New record created successfully'     
    return jsonify(msg)
    
if __name__ == "__main__":
    app.run(debug=True)
index.html
//index.html
<!DOCTYPE html>
<html>
 <head>
  <title>Python Flask Create a Progress Bar Data Insert using Jquery Ajax Bootstrap and Mysqldb database</title>  
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
 $(document).ready(function(){
 $('#sample_form').on('submit', function(event){
   event.preventDefault();
   var count_error = 0;
 
   if($('#username').val() == '')
   {
    $('#first_name_error').text('User Name is required');
    count_error++;
   }
   else
   {
    $('#first_name_error').text('');
   }
 
   if($('#useremail').val() == '')
   {
    $('#last_name_error').text('Email is required');
    count_error++;
   }
   else
   {
    $('#last_name_error').text('');
   }
 
   if(count_error == 0)
   {
    $.ajax({
   url:"/ajaxprogressbar",
   method:"POST",
   data:$(this).serialize(),
   beforeSend:function()
   {
    $('#save').attr('disabled', 'disabled');
    $('#process').css('display', 'block');
   },
   success:function(data)
   { 
    var percentage = 0;
 
    var timer = setInterval(function(){
     percentage = percentage + 20;
     progress_bar_process(percentage, timer,data);
    }, 1000);
   }
  })
   }
   else
   {
    return false;
   }
    
  });
   
  function progress_bar_process(percentage, timer,data)
  {
 $('.progress-bar').css('width', percentage + '%');
 if(percentage > 100)
 {
  clearInterval(timer);
  $('#sample_form')[0].reset();
  $('#process').css('display', 'none');
  $('.progress-bar').css('width', '0%');
  $('#save').attr('disabled', false);
  $('#success_message').html(data);
  setTimeout(function(){
   $('#success_message').html('');
  }, 5000);
 }
  }
   
 });
</script>
 </head>
 <body>
  <br />
  <br />
  <div class="container">
   <h1 align="center">Python Flask Create a Progress Bar Data Insert using Jquery Ajax Bootstrap and Mysqldb database</h1>
   <br />
   <div class="panel panel-default">
    <div class="panel-heading">
     <h3 class="panel-title">Registration</h3>
    </div>
      <div class="panel-body">
       <span id="success_message"></span>
       <form method="post" id="sample_form">
     <div class="form-group">
        <label>User Name</label>
         <input type="text" name="username" id="username" class="form-control" />
         <span id="first_name_error" class="text-danger"></span>
        </div>
  <div class="form-group">
         <label>Email</label>
         <input type="text" name="useremail" id="useremail" class="form-control" />
         <span id="last_name_error" class="text-danger"></span>
        </div>
  <div class="form-group" align="center">
         <input type="submit" name="save" id="save" class="btn btn-info" value="Save" />
        </div>
       </form>
       <div class="form-group" id="process" style="display:none;">
        <div class="progress">
       <div class="progress-bar progress-bar-striped active bg-success" role="progressbar" aria-valuemin="0" aria-valuemax="100" style=""></div>
      </div>
       </div>
      </div>
     </div>
  </div>
 </body>
</html>

Monday, December 28, 2020

Insert View Data Through Bootstrap Modal using Python Flask and Jquery Ajax MysqlDB

Insert View Data Through Bootstrap Modal using Python Flask and Jquery Ajax MysqlDB

--
-- Table structure for table `tbl_employee`
--

CREATE TABLE `tbl_employee` (
  `id` int(11) NOT NULL,
  `name` varchar(50) NOT NULL,
  `address` text NOT NULL,
  `gender` varchar(10) NOT NULL,
  `designation` varchar(100) NOT NULL,
  `age` int(11) NOT NULL,
  `image` varchar(100) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tbl_employee`
--

INSERT INTO `tbl_employee` (`id`, `name`, `address`, `gender`, `designation`, `age`, `image`) VALUES
(214, 'Ashton Cox', 'San Francisco', 'Male', 'Junior Technical Author', 46, ''),
(213, 'Angelica Ramos', 'London', 'Male', 'Chief Executive Officer (CEO)', 45, ''),
(212, 'Airi Satou', 'Tokyo', 'Male', 'Accountant', 78, '');
app.py
#app.py
from flask import Flask, render_template, request, redirect, flash, jsonify, json
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 main():	
    cursor = mysql.connection.cursor()
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    result = cur.execute("SELECT * FROM tbl_employee ORDER BY id")
    employee = cur.fetchall()	
    return render_template('index.html', employee=employee)
    
@app.route('/insert', methods=['GET', 'POST'])
def insert():   
    cursor = mysql.connection.cursor()
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    if request.method == 'POST': 
        name = request.form['name']
        address = request.form['address']
        gender = request.form['gender']
        designation = request.form['designation']
        age = request.form['age']
        cur.execute("INSERT INTO tbl_employee (name, address, gender, designation, age) VALUES (%s, %s, %s, %s, %s)",[name, address, gender, designation, age])
        mysql.connection.commit()
        cur.close()
    return jsonify('success')

@app.route('/select', methods=['GET', 'POST'])
def select():   
    cursor = mysql.connection.cursor()
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    if request.method == 'POST': 
        employee_id = request.form['employee_id']
        print(employee_id)		
        result = cur.execute("SELECT * FROM tbl_employee WHERE id = %s", [employee_id])
        rsemployee = cur.fetchall()
        employeearray = []
        for rs in rsemployee:
            employee_dict = {
                    'Id': rs['id'],
                    'emp_name': rs['name'],
                    'address': rs['address'],
                    'gender': rs['gender'],
                    'designation': rs['designation'],
                    'age': rs['age']}
            employeearray.append(employee_dict)
        return json.dumps(employeearray)
	
if __name__ == '__main__':
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>  
<html>  
 <head>  
  <title>Insert View Data Through Bootstrap Modal using Python Flask and Jquery Ajax MysqlDB</title>  
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>  
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
 </head>  
 <body>  
  <br /><br />  
  <div class="container" style="width:700px;">  
   <h3 align="center">Insert View Data Through Bootstrap Modal using Python Flask and Jquery Ajax MysqlDB</h3>  
   <br />   
   <div class="table-responsive">
    <div align="right">
     <button type="button" name="age" id="age" data-toggle="modal" data-target="#add_data_Modal" class="btn btn-warning">Add</button>
    </div>
    <br />
    <div id="employee_table">
     <table class="table table-bordered">
      <tr>
       <th width="70%">Employee Name</th>  
       <th width="30%">View</th>
      </tr>
      {% for row in employee %}
      <tr>
       <td>{{row.name}}</td>
       <td><input type="button" name="view" value="view" id="{{row.id}}" class="btn btn-info btn-xs view_data" /></td>
      </tr>
      {% endfor %}
     </table>
    </div>
   </div> 

  
  </div>
<div id="add_data_Modal" class="modal fade">
 <div class="modal-dialog">
  <div class="modal-content">
   <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal">×</button>
    <h4 class="modal-title">Insert View Data Through Bootstrap Modal using Jquery Ajax and python flask Mysql</h4>
   </div>
   <div class="modal-body">
    <form method="post" id="insert_form">
     <label>Enter Employee Name</label>
     <input type="text" name="name" id="name" class="form-control" />
     <br />
     <label>Enter Employee Address</label>
     <textarea name="address" id="address" class="form-control"></textarea>
     <br />
     <label>Select Gender</label>
     <select name="gender" id="gender" class="form-control">
      <option value="Male">Male</option>  
      <option value="Female">Female</option>
     </select>
     <br />  
     <label>Enter Designation</label>
     <input type="text" name="designation" id="designation" class="form-control" />
     <br />  
     <label>Enter Age</label>
     <input type="text" name="age" id="age" class="form-control" />
     <br />
     <input type="submit" name="insert" id="insert" value="Insert" class="btn btn-success" />

    </form>
   </div>
   <div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
   </div>
  </div>
 </div>
</div>

<div id="dataModal" class="modal fade">
 <div class="modal-dialog">
  <div class="modal-content">
   <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal">×</button>
    <h4 class="modal-title">Employee Details</h4>
   </div>
   <div class="modal-body">
      <div class="table-responsive">  
        <table class="table table-bordered">
		<tr>  
            <td width="30%"><label>Name</label></td>  
            <td width="70%"><input type="text" class="form-control" id="view_name"></td>  
        </tr>
        <tr>  
            <td width="30%"><label>Address</label></td>  
            <td width="70%"><input type="text" class="form-control" id="view_address"></td>  
        </tr>
        <tr>  
            <td width="30%"><label>Gender</label></td>  
            <td width="70%"><input type="text" class="form-control" id="view_gender"></td>  
        </tr>
        <tr>  
            <td width="30%"><label>Designation</label></td>  
            <td width="70%"><input type="text" class="form-control" id="view_designation"></td>  
        </tr>
        <tr>  
            <td width="30%"><label>Age</label></td>  
            <td width="70%"><input type="text" class="form-control" id="view_age"></td>  
        </tr>
    </table></div>
   </div>
   <div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
   </div>
  </div>
 </div>
</div>

<script>  
$(document).ready(function(){
 $('#insert_form').on("submit", function(event){  
  event.preventDefault();  
  if($('#name').val() == "")  
  {  
   alert("Name is required");  
  }  
  else if($('#address').val() == '')  
  {  
   alert("Address is required");  
  }  
  else if($('#designation').val() == '')
  {  
   alert("Designation is required");  
  }
   
  else  
  {  
   $.ajax({  
    url:"/insert",  
    method:"POST",  
    data:$('#insert_form').serialize(),  
    beforeSend:function(){  
     $('#insert').val("Inserting");  
    },  
    success:function(data){  
     $('#add_data_Modal').modal('hide'); 
	  if (data=='success')	{
       window.location.href = "/";	 
	 }
    }  
   });  
  }  
 });

 $(document).on('click', '.view_data', function(){
  var employee_id = $(this).attr("id");
  $.ajax({
   url:"/select",
   method:"POST",
   data:{employee_id:employee_id},
   success:function(data){
    $('#dataModal').modal('show');
	var data_rs = JSON.parse(data);
	$('#view_name').val(data_rs[0]['emp_name']);
	$('#view_address').val(data_rs[0]['address']);
	$('#view_gender').val(data_rs[0]['gender']);
	$('#view_designation').val(data_rs[0]['designation']);
	$('#view_age').val(data_rs[0]['age']);
   }
  });
 });
});  
 </script>  
 </body>  
</html>  

Insert View Data Through Bootstrap Modal using Jquery Ajax and PHP Mysql

Insert View Data Through Bootstrap Modal using Jquery Ajax and PHP Mysql

--
-- Table structure for table `tbl_employee`
--

CREATE TABLE `tbl_employee` (
  `id` int(11) NOT NULL,
  `name` varchar(50) NOT NULL,
  `address` text NOT NULL,
  `gender` varchar(10) NOT NULL,
  `designation` varchar(100) NOT NULL,
  `age` int(11) NOT NULL,
  `image` varchar(100) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tbl_employee`
--

INSERT INTO `tbl_employee` (`id`, `name`, `address`, `gender`, `designation`, `age`, `image`) VALUES
(214, 'Ashton Cox', 'San Francisco', 'Male', 'Junior Technical Author', 46, ''),
(213, 'Angelica Ramos', 'London', 'Male', 'Chief Executive Officer (CEO)', 45, ''),
(212, 'Airi Satou', 'Tokyo', 'Male', 'Accountant', 78, '');

//index.php
 <!DOCTYPE html>  
<html>  
 <head>  
  <title>Insert View Data Through Bootstrap Modal using Jquery Ajax and PHP Mysql</title>  
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>  
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
 </head>  
 <body>  
  <br /><br />  
  <div class="container" style="width:700px;">  
   <h3 align="center">Insert View Data Through Bootstrap Modal using Jquery Ajax and PHP Mysql</h3>  
   <br />  
   <div class="table-responsive">
    <div align="right">
     <button type="button" name="age" id="age" data-toggle="modal" data-target="#add_data_Modal" class="btn btn-warning">Add</button>
    </div>
    <br />
<?php  
//index.php
$connect = mysqli_connect("localhost", "root", "", "testingdb");
$query = "SELECT * FROM tbl_employee ORDER BY id DESC";
$result = mysqli_query($connect, $query);
 ?> 
    <div id="employee_table">
     <table class="table table-bordered">
      <tr>
       <th width="70%">Employee Name</th>  
       <th width="30%">View</th>
      </tr>
      <?php
      while($row = mysqli_fetch_array($result))
      {
      ?>
      <tr>
       <td><?php echo $row["name"]; ?></td>
       <td><input type="button" name="view" value="view" id="<?php echo $row["id"]; ?>" class="btn btn-info btn-xs view_data" /></td>
      </tr>
      <?php
      }
      ?>
     </table>
    </div>
   </div>  
  </div>
<div id="add_data_Modal" class="modal fade">
 <div class="modal-dialog">
  <div class="modal-content">
   <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal">×</button>
    <h4 class="modal-title">Insert View Data Through Bootstrap Modal using Jquery Ajax and PHP Mysql</h4>
   </div>
   <div class="modal-body">
    <form method="post" id="insert_form">
     <label>Enter Employee Name</label>
     <input type="text" name="name" id="name" class="form-control" />
     <br />
     <label>Enter Employee Address</label>
     <textarea name="address" id="address" class="form-control"></textarea>
     <br />
     <label>Select Gender</label>
     <select name="gender" id="gender" class="form-control">
      <option value="Male">Male</option>  
      <option value="Female">Female</option>
     </select>
     <br />  
     <label>Enter Designation</label>
     <input type="text" name="designation" id="designation" class="form-control" />
     <br />  
     <label>Enter Age</label>
     <input type="text" name="age" id="age" class="form-control" />
     <br />
     <input type="submit" name="insert" id="insert" value="Insert" class="btn btn-success" />

    </form>
   </div>
   <div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
   </div>
  </div>
 </div>
</div>

<div id="dataModal" class="modal fade">
 <div class="modal-dialog">
  <div class="modal-content">
   <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal">×</button>
    <h4 class="modal-title">Employee Details</h4>
   </div>
   <div class="modal-body" id="employee_detail">
    
   </div>
   <div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
   </div>
  </div>
 </div>
</div>

<script>  
$(document).ready(function(){
 $('#insert_form').on("submit", function(event){  
  event.preventDefault();  
  if($('#name').val() == "")  
  {  
   alert("Name is required");  
  }  
  else if($('#address').val() == '')  
  {  
   alert("Address is required");  
  }  
  else if($('#designation').val() == '')
  {  
   alert("Designation is required");  
  }
   
  else  
  {  
   $.ajax({  
    url:"insert.php",  
    method:"POST",  
    data:$('#insert_form').serialize(),  
    beforeSend:function(){  
     $('#insert').val("Inserting");  
    },  
    success:function(data){  
     $('#insert_form')[0].reset();  
     $('#add_data_Modal').modal('hide');  
     $('#employee_table').html(data);  
    }  
   });  
  }  
 });




 $(document).on('click', '.view_data', function(){
  //$('#dataModal').modal();
  var employee_id = $(this).attr("id");
  $.ajax({
   url:"select.php",
   method:"POST",
   data:{employee_id:employee_id},
   success:function(data){
    $('#employee_detail').html(data);
    $('#dataModal').modal('show');
   }
  });
 });
});  
 </script>  
 </body>  
</html>  
insert.php
//insert.php
<?php
//insert.php  
$connect = mysqli_connect("localhost", "root", "", "testingdb");
if(!empty($_POST))
{
 $output = '';
 $name = mysqli_real_escape_string($connect, $_POST["name"]);  
    $address = mysqli_real_escape_string($connect, $_POST["address"]);  
    $gender = mysqli_real_escape_string($connect, $_POST["gender"]);  
    $designation = mysqli_real_escape_string($connect, $_POST["designation"]);  
    $age = mysqli_real_escape_string($connect, $_POST["age"]);
    $query = "
    INSERT INTO tbl_employee(name, address, gender, designation, age)  
     VALUES('$name', '$address', '$gender', '$designation', '$age')
    ";
    if(mysqli_query($connect, $query))
    {
     $output .= '<label class="text-success">Data Inserted</label>';
     $select_query = "SELECT * FROM tbl_employee ORDER BY id DESC";
     $result = mysqli_query($connect, $select_query);
     $output .= '
      <table class="table table-bordered">  
                    <tr>  
                         <th width="70%">Employee Name</th>  
                         <th width="30%">View</th>  
                    </tr>

     ';
     while($row = mysqli_fetch_array($result))
     {
      $output .= '
       <tr>  
                         <td>' . $row["name"] . '</td>  
                         <td><input type="button" name="view" value="view" id="' . $row["id"] . '" class="btn btn-info btn-xs view_data" /></td>  
                    </tr>
      ';
     }
     $output .= '</table>';
    }
    echo $output;
}
?>
select.php
//select.php
<?php  
//select.php  
if(isset($_POST["employee_id"]))
{
 $output = '';
 $connect = mysqli_connect("localhost", "root", "", "testingdb");
 $query = "SELECT * FROM tbl_employee WHERE id = '".$_POST["employee_id"]."'";
 $result = mysqli_query($connect, $query);
 $output .= '  
      <div class="table-responsive">  
           <table class="table table-bordered">';
    while($row = mysqli_fetch_array($result))
    {
     $output .= '
     <tr>  
            <td width="30%"><label>Name</label></td>  
            <td width="70%">'.$row["name"].'</td>  
        </tr>
        <tr>  
            <td width="30%"><label>Address</label></td>  
            <td width="70%">'.$row["address"].'</td>  
        </tr>
        <tr>  
            <td width="30%"><label>Gender</label></td>  
            <td width="70%">'.$row["gender"].'</td>  
        </tr>
        <tr>  
            <td width="30%"><label>Designation</label></td>  
            <td width="70%">'.$row["designation"].'</td>  
        </tr>
        <tr>  
            <td width="30%"><label>Age</label></td>  
            <td width="70%">'.$row["age"].'</td>  
        </tr>
     ';
    }
    $output .= '</table></div>';
    echo $output;
}
?>

Saturday, December 26, 2020

Delete multiple records by selecting checkboxes using Python Flask with MySQLdb

Delete multiple records by selecting checkboxes using Python Flask with MySQLdb

app.py
 
#app.py
from flask import Flask, render_template, request, redirect, flash
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 main():	
    cursor = mysql.connection.cursor()
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    result = cur.execute("SELECT * FROM contacts ORDER BY id")
    contacts = cur.fetchall()	
    return render_template('index.html', contacts=contacts)
    
@app.route('/delete', methods=['GET', 'POST'])
def delete():	
    cursor = mysql.connection.cursor()
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    if request.method == 'POST': 
        for getid in request.form.getlist('mycheckbox'):
            print(getid)
            cur.execute('DELETE FROM contacts WHERE id = {0}'.format(getid))
            mysql.connection.commit()
        flash('Successfully Deleted!')
    return redirect('/')
		
if __name__ == '__main__':
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html>
 <head>
  <title>Delete multiple records by selecting checkboxes using Python Flask with MySQLdb</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
 </head>
 <body>
  <div class="container">
   <br />
   <h3 align="center">Delete multiple records by selecting checkboxes using Python Flask with MySQLdb</h3><br />
   <form method="POST" action="/delete">
   <div class="table-responsive">
    <table class="table table-bordered">
     <tr>
      <th>Name</th>
      <th>Phone</th>
      <th>Email</th>
      <th>Delete</th>
     </tr>
	 {% for row in contacts %}
     <tr id="{{row.id}}" >
      <td>{{row.fullname}}</td>
      <td>{{row.phone}}</td>
      <td>{{row.email}}</td>
      <td><input type="checkbox" name="mycheckbox" value="{{row.id}}" /></td>
     </tr>
	 {% endfor %}
    </table>
   </div>
   <div align="center">
     {% with messages = get_flashed_messages() %}
       {% if messages %}
      {% for message in messages %}
      <div class="alert alert-danger" role="alert">{{ message }}</div>
      {% endfor %}
      {% endif %}
     {% endwith %}
	<input type="submit" value="Delete All Selected" class="btn btn-primary">  
   </div>
   </form>  
 </body>
</html>

Delete multiple records by selecting checkboxes using Jquery Ajax and PHP Mysqli

Delete multiple records by selecting checkboxes using Jquery Ajax and PHP Mysqli


//checkbox_multiple_delete.php
<!DOCTYPE html>
<html>
 <head>
  <title>Delete multiple records by selecting checkboxes using Jquery Ajax and PHP Mysqli</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <style>
   #box {
    width:600px;
    background:gray;
    color:white;
    margin:0 auto;
    padding:10px;
    text-align:center;
   }
  </style>
 </head>
 <body>
  <div class="container">
   <br />
   <h3 align="center">Delete multiple records by selecting checkboxes using Jquery Ajax and PHP Mysqli</h3><br />
   <?php 
$connect = mysqli_connect("localhost", "root", "", "testingdb");
$query = "SELECT * FROM contacts";
$result = mysqli_query($connect, $query);
   if(mysqli_num_rows($result) > 0)
   {
   ?>
   <div class="table-responsive">
    <table class="table table-bordered">
     <tr>
      <th>Name</th>
      <th>Phone</th>
      <th>Email</th>
      <th>Delete</th>
     </tr>
   <?php
    while($row = mysqli_fetch_array($result))
    {
   ?>
     <tr id="<?php echo $row["id"]; ?>" >
      <td><?php echo $row["fullname"]; ?></td>
      <td><?php echo $row["phone"]; ?></td>
      <td><?php echo $row["email"]; ?></td>
      <td><input type="checkbox" name="customer_id[]" class="delete_customer" value="<?php echo $row["id"]; ?>" /></td>
     </tr>
   <?php
    }
   ?>
    </table>
   </div>
   <?php
   }
   ?>
   <div align="center">
    <button type="button" name="btn_delete" id="btn_delete" class="btn btn-success">Delete</button>
   </div>
<script>
$(document).ready(function(){
  $('#btn_delete').click(function(){
  if(confirm("Are you sure you want to delete this?")) {
    var id = [];
    $(':checkbox:checked').each(function(i){
     id[i] = $(this).val();
    });
   if(id.length === 0) //tell you if the array is empty
   {
    alert("Please Select atleast one checkbox");
   }else {
    $.ajax({
     url:'delete.php',
     method:'POST',
     data:{id:id},
     success:function()
     { alert(id)
      for(var i=0; i<id.length; i++)
      {
       $('tr#'+id[i]+'').css('background-color', '#ccc');
       $('tr#'+id[i]+'').fadeOut('slow');
      }
     }
     
    });
   }
  }else{
   return false;
  }
 });
});
</script>   
 </body>
</html>
delete.php
//delete.php
<?php
//delete.php
$connect = mysqli_connect("localhost", "root", "", "testingdb");
if(isset($_POST["id"]))
{
 foreach($_POST["id"] as $id)
 {
  $query = "DELETE FROM contacts WHERE id = '".$id."'";
  mysqli_query($connect, $query);
 }
}
?>

Friday, December 25, 2020

Dependent Dropdown with Search Box using Python Flask jQuery, Ajax, and MySQLdb Database

Dependent Dropdown with Search Box using Python Flask jQuery, Ajax, and MySQLdb Database

bootstrap-select plugin https://developer.snapappointments.com/bootstrap-select/

--
-- Table structure for table `carbrands`
--

CREATE TABLE `carbrands` (
  `brand_id` int(11) NOT NULL,
  `brand_name` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `carbrands`
--

INSERT INTO `carbrands` (`brand_id`, `brand_name`) VALUES
(1, 'Toyota'),
(2, 'Honda'),
(3, 'Suzuki'),
(4, 'Mitsubishi'),
(5, 'Hyundai');

--
-- Table structure for table `carmodels`
--

CREATE TABLE `carmodels` (
  `model_id` int(11) NOT NULL,
  `brand_id` int(11) NOT NULL,
  `car_models` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `carmodels`
--

INSERT INTO `carmodels` (`model_id`, `brand_id`, `car_models`) VALUES
(1, 1, 'Toyota Corolla'),
(2, 2, 'Toyota Camry'),
(3, 1, 'Toyota Yaris'),
(4, 1, 'Toyota Sienna'),
(5, 1, 'Toyota RAV4'),
(6, 1, 'Toyota Highlander'),
(7, 2, 'Honda HR-V'),
(8, 2, 'Honda Odyssey'),
(9, 3, 'Swift'),
(10, 3, 'Celerio'),
(11, 3, 'Ertiga'),
(12, 3, 'Vitara'),
(13, 4, 'Mirage'),
(14, 4, 'Mirage G4'),
(15, 4, 'Xpander Cross'),
(16, 4, 'Montero Sport'),
(17, 4, 'Strada Athlete'),
(18, 5, 'Reina '),
(19, 5, 'Accent'),
(20, 5, 'Elantra'),
(21, 5, 'Tucson');
app.py
#app.py
from flask import Flask, render_template, jsonify, request
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 main():
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    result = cur.execute("SELECT * FROM carbrands ORDER BY brand_id")
    carbrands = cur.fetchall()
    return render_template('index.html', carbrands=carbrands)

@app.route("/carbrand",methods=["POST","GET"])
def carbrand():  
    cursor = mysql.connection.cursor()
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    if request.method == 'POST':
        category_id = request.form['category_id'] 
        print(category_id)	
        result = cur.execute("SELECT * FROM carmodels WHERE brand_id = %s ORDER BY car_models ASC", [category_id] )
        carmodel = cur.fetchall()  
        OutputArray = []
        for row in carmodel:
            outputObj = {
                'id': row['brand_id'],
                'name': row['car_models']}
            OutputArray.append(outputObj)
    return jsonify(OutputArray)
	
if __name__ == '__main__':
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html>
    <head>
        <title>Dependent Dropdown with Search Box using Python Flask jQuery, Ajax, and MySQLdb Database</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" />
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/css/bootstrap-select.min.css" />
    </head>
    <body>
        <div class="container">
            <h1 align="center">Dependent Dropdown with Search Box using Python Flask jQuery, Ajax, and MySQLdb Database</h1>       
            <div class="row">
                <div class="col-md-6">
                    <label>Select Car</label>
                    <select name="car_brand" data-live-search="true" id="car_brand" class="form-control" title="Select Car Brand"> 
					{% for row in carbrands %}
					<option value="{{row.brand_id}}">{{row.brand_name}}</option>
					{% endfor %}
					</select>
                </div>
                <div class="col-md-6">
                    <label>Select Brand</label>
                    <select name="car_models" data-live-search="true" id="car_models" class="form-control" title="Select Car Model"> </select>
                </div>
            </div>
        </div>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/js/bootstrap-select.min.js"></script>
        <script>
            $(document).ready(function () {
                $("#car_brand").selectpicker();
  
                $("#car_models").selectpicker();
  
                function load_data(type, category_id) {
                    $.ajax({
                        url: "/carbrand",
                        method: "POST",
                        data: { type: type, category_id: category_id },
                        dataType: "json",
                        success: function (data) { //alert(category_id)
                            var html = "";
                            for (var count = 0; count < data.length; count++) {
                                html += '<option value="' + data[count].id + '">' + data[count].name + "</option>";
                            }
                            if (type == "carData") {
                                $("#car_brand").html(html);
                                $("#car_brand").selectpicker("refresh");
                            } else {
                                $("#car_models").html(html);
                                $("#car_models").selectpicker("refresh");
                            }
                        },
                    });
                }
  
                $(document).on("change", "#car_brand", function () {
                    var category_id = $("#car_brand").val();
                    load_data("carModeldata", category_id);
                });
            });
        </script>
    </body>
</html>

Dependent Dropdown with Search Box using jQuery, Ajax, and PHP mysqli

Dependent Dropdown with Search Box using jQuery, Ajax, and PHP mysqli

bootstrap-select plugin https://developer.snapappointments.com/bootstrap-select/

--
-- Table structure for table `carbrands`
--

CREATE TABLE `carbrands` (
  `brand_id` int(11) NOT NULL,
  `brand_name` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `carbrands`
--

INSERT INTO `carbrands` (`brand_id`, `brand_name`) VALUES
(1, 'Toyota'),
(2, 'Honda'),
(3, 'Suzuki'),
(4, 'Mitsubishi'),
(5, 'Hyundai');

--
-- Table structure for table `carmodels`
--

CREATE TABLE `carmodels` (
  `model_id` int(11) NOT NULL,
  `brand_id` int(11) NOT NULL,
  `car_models` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `carmodels`
--

INSERT INTO `carmodels` (`model_id`, `brand_id`, `car_models`) VALUES
(1, 1, 'Toyota Corolla'),
(2, 2, 'Toyota Camry'),
(3, 1, 'Toyota Yaris'),
(4, 1, 'Toyota Sienna'),
(5, 1, 'Toyota RAV4'),
(6, 1, 'Toyota Highlander'),
(7, 2, 'Honda HR-V'),
(8, 2, 'Honda Odyssey'),
(9, 3, 'Swift'),
(10, 3, 'Celerio'),
(11, 3, 'Ertiga'),
(12, 3, 'Vitara'),
(13, 4, 'Mirage'),
(14, 4, 'Mirage G4'),
(15, 4, 'Xpander Cross'),
(16, 4, 'Montero Sport'),
(17, 4, 'Strada Athlete'),
(18, 5, 'Reina '),
(19, 5, 'Accent'),
(20, 5, 'Elantra'),
(21, 5, 'Tucson');

//searchbox_depdendet_dropdown.php
<!DOCTYPE html>
<html>
    <head>
        <title>Dependent Dropdown with Search Box using jQuery, Ajax, and PHP mysqli</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" />
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/css/bootstrap-select.min.css" />
    </head>
    <body>
        <div class="container">
            <h1 align="center">Dependent Dropdown with Search Box using jQuery, Ajax, and PHP mysqli</h1>		
            <div class="row">
                <div class="col-md-6">
                    <label>Select Car</label>
                    <select name="car_brand" data-live-search="true" id="car_brand" class="form-control" title="Select Car Brand"> </select>
                </div>
                <div class="col-md-6">
                    <label>Select Brand</label>
                    <select name="car_models" data-live-search="true" id="car_models" class="form-control" title="Select Car Model"> </select>
                </div>
            </div>
        </div>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/js/bootstrap-select.min.js"></script>
        <script>
            $(document).ready(function () {
                $("#car_brand").selectpicker();
 
                $("#car_models").selectpicker();
 
                load_data("carData");
 
                function load_data(type, category_id = "") {
                    $.ajax({
                        url: "fetch.php",
                        method: "POST",
                        data: { type: type, category_id: category_id },
                        dataType: "json",
                        success: function (data) {
                            var html = "";
                            for (var count = 0; count < data.length; count++) {
                                html += '<option value="' + data[count].id + '">' + data[count].name + "</option>";
                            }
                            if (type == "carData") {
                                $("#car_brand").html(html);
                                $("#car_brand").selectpicker("refresh");
                            } else {
                                $("#car_models").html(html);
                                $("#car_models").selectpicker("refresh");
                            }
                        },
                    });
                }
 
                $(document).on("change", "#car_brand", function () {
                    var category_id = $("#car_brand").val();
                    load_data("carModeldata", category_id);
                });
            });
        </script>
    </body>
</html>
fetch.php
//fetch.php
<?php
$conn = mysqli_connect("localhost", "root", "", "testingdb");

if (isset($_POST["type"])) {
    if ($_POST["type"] == "carData") {
		$sqlQuery = "SELECT * FROM carBrands ORDER BY brand_name ASC";
		$resultset = mysqli_query($conn, $sqlQuery) or die("database error:". mysqli_error($conn));
		while( $row = mysqli_fetch_array($resultset) ) {
			$output[] = [
				'id' => $row["brand_id"],
				'name' => $row["brand_name"],
			];
		}
        echo json_encode($output); 
    } else {
		$sqlQuery2 = "SELECT * FROM carModels WHERE brand_id = '" . $_POST["category_id"] . "' ORDER BY car_models ASC";
		$resultset2 = mysqli_query($conn, $sqlQuery2) or die("database error:". mysqli_error($conn));
		while( $row2 = mysqli_fetch_array($resultset2) ) {
			$output[] = [
				'id' => $row2["model_id"],
				'name' => $row2["car_models"],
			];
		}
		echo json_encode($output);
    }
}
 
?>

Thursday, December 24, 2020

Insert Checkbox values in Database using Python Flask Jquery Ajax and MySQLdb

Insert Checkbox values in Database using Python Flask Jquery Ajax and MySQLdb

--
-- Table structure for table `checkbox`
--

CREATE TABLE `checkbox` (
  `id` int(11) NOT NULL,
  `name` varchar(155) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

app.py
 
#app.py
from flask import Flask, render_template, jsonify, request
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 main():
    return render_template('index.html')

@app.route("/insert",methods=["POST","GET"])
def insert():  
    cursor = mysql.connection.cursor()
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    if request.method == 'POST':
        insert = request.form['checkboxvalue'] 
        cur.execute("INSERT INTO checkbox (name) VALUES (%s)",[insert])
        mysql.connection.commit()
        cur.close()	
        msg = 'Data Inserted Successfully!'
    else:
        msg = 'Invalid'
    return jsonify(msg)
	
if __name__ == '__main__':
    app.run(debug=True)
templates/index.html
//templates/index.html
<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Insert Checkbox values in Database using Python Flask Jquery Ajax and MySQLdb</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
    <h3>Insert Checkbox values in Database using Python Flask Jquery Ajax and MySQLdb</h3>
    <label><input type="checkbox" class="get_value" value="Python"> Python</label>
    <br/>
    <label> <input type="checkbox" class="get_value" value="JavaScript"> JavaScript</label>
    <br/>
    <label><input type="checkbox" class="get_value" value="Java"> Java</label>
    <br/>
    <label><input type="checkbox" class="get_value" value="PHP"> PHP</label>
    <br/>
    <label><input type="checkbox" class="get_value" value="C#"> C#</label>
    <br/>
    <br/>
    <button type="button" name="submit" id="submit">Save</button>
    <br/>
    <h4 id="result"></h4>
    <script>
        $(document).ready(function() {
            $('#submit').click(function() {
                var insert = [];
                $('.get_value').each(function() {
                    if ($(this).is(":checked")) {
                        insert.push($(this).val());
                    }
                });
                insert = insert.toString();			
				var insert_string = 'checkboxvalue='+insert;			
				$.ajax({
					method: "POST",
					url: "/insert",
					data: insert_string,
					cache: false,
					success: function(data){    
						$("#result").html(data);
					}
				});
            });
        });
    </script>
</body>
</html>

Insert Checkbox values in Database using Jquery Ajax and PHP Mysqli

Insert Checkbox values in Database using Jquery Ajax and PHP Mysqli

--
-- Table structure for table `checkbox`
--

CREATE TABLE `checkbox` (
  `id` int(11) NOT NULL,
  `name` varchar(155) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Insert Checkbox values in Database using Jquery Ajax and PHP Mysqli</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
    <h3>Insert Checkbox values in Database using Jquery Ajax and PHP Mysqli</h3>
    <input type="checkbox" class="get_value" value="Python">
    <label>Python</label>
    <br/>
    <input type="checkbox" class="get_value" value="JavaScript">
    <label>JavaScript</label>
    <br/>
    <input type="checkbox" class="get_value" value="Java">
    <label>Java</label>
    <br/>
    <input type="checkbox" class="get_value" value="PHP">
    <label>PHP</label>
    <br/>
    <input type="checkbox" class="get_value" value="C#">
    <label>C#</label>
    <br/>
    <br/>
    <button type="button" name="submit" id="submit">Save</button>
    <br/>
    <h4 id="result"></h4>
    <script>
        $(document).ready(function() {
            $('#submit').click(function() {
                var insert = [];
                $('.get_value').each(function() {
                    if ($(this).is(":checked")) {
                        insert.push($(this).val());
                    }
                });
                insert = insert.toString();
                $.ajax({
                    url: "insert.php",
                    method: "POST",
                    data: {
                        insert: insert
                    },
                    success: function(data) {
                        $('#result').html(data);
                    }
                });
            });
        });
    </script>
</body>
</html>
insert.php
//insert.php
<?php
if(isset($_POST["insert"]))
{
 $query = "INSERT INTO checkbox(name) VALUES ('".$_POST["insert"]."')";
 $result = mysqli_query($conn, $query);
 echo "Data Inserted Successfully!";
}
?>
//dbcon.php
<?php
$conn = new mysqli('localhost','root','','testingdb');
if ($conn->connect_error) {
    die('Error : ('. $conn->connect_errno .') '. $conn->connect_error);
}
?>

Monday, December 21, 2020

TinyMCE Upload Image with Python Flask and Jquery Ajax

 


TinyMCE Upload Image with Python Flask and Jquery Ajax

TinyMCE is a well known WYSIWYG HTML Editor which extensively used in web applications to create HTML contents. It supports text formatting, table insert, link insert, image insert and more features.

Download from website https://www.tiny.cloud/


app.py
#app.py
from flask import Flask, render_template, jsonify, request
from werkzeug.utils import secure_filename
import os
#import magic
import urllib.request

app = Flask(__name__)

UPLOAD_FOLDER = 'static/uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
  
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
  
def allowed_file(filename):
 return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
 
@app.route('/')
def main():
    return render_template('index.html')
 

@app.route("/upload",methods=["POST","GET"])
def upload():  
    if request.method == 'POST':
        file = request.files['file']
        filename = secure_filename(file.filename)
         
        if file and allowed_file(file.filename):
           file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
           print('File successfully uploaded ' + file.filename + ' to static/upload')
        else:
           print('Invalid Uplaod only png, jpg, jpeg, gif')   
    return jsonify(filename)
	
if __name__ == '__main__':
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>TinyMCE Upload Image with Python Flask and Jquery Ajax</title> 
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<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.5/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
</head>
<body class="">
<div class="container">	
	<div class="row">	
		<h2>TinyMCE Upload Image with Python Flask and Jquery Ajax</h2>				
		<form id="posts" name="posts" method="post">
			<textarea name="message" id="message"></textarea><br>				
		</form>		
	</div>	
</div>
<script src="/static/tinymce/tinymce.min.js"></script>
<script>
tinymce.init({
	selector: "textarea",
	plugins: "code",
	toolbar: "undo redo | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link code image_upload",
	menubar:false,
    statusbar: false,
	content_style: ".mce-content-body {font-size:15px;font-family:Arial,sans-serif;}",
	height: 400,
	setup: function(ed) {
		
		var fileInput = $('<input id="tinymce-uploader" type="file" name="pic" accept="image/*" style="display:none">');
		$(ed.getElement()).parent().append(fileInput);
		
		fileInput.on("change",function(){			
			var file = this.files[0];
			var reader = new FileReader();			
			var formData = new FormData();
			var files = file;
			formData.append("file",files);
			formData.append('filetype', 'image');				
			jQuery.ajax({
				url: "/upload",
				type: "post",
				data: formData,
				contentType: false,
				processData: false,
				async: false,
				success: function(response){
					var fileName = response;
					if(fileName) {
						ed.insertContent('<img src="/static/uploads/'+fileName+'"/>');
					}
				}
			});		
			reader.readAsDataURL(file);	 
		});		
		
		ed.addButton('image_upload', {
			tooltip: 'Upload Image',
			icon: 'image',
			onclick: function () {
				fileInput.trigger('click');
			}
		});
	}
});
</script>
</body>
</html>

TinyMCE Upload Image with Jquery Ajax and PHP

TinyMCE Upload Image with Jquery Ajax and PHP

TinyMCE is a well known WYSIWYG HTML Editor which extensively used in web applications to create HTML contents. It supports text formatting, table insert, link insert, image insert and more features.

Download from website https://www.tiny.cloud/


tinymce_imageupload.php
//tinymce_imageupload.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>TinyMCE Upload Image with Jquery Ajax and PHP</title> 
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<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.5/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
</head>
<body class="">
<div class="container">	
	<div class="row">	
		<h2>TinyMCE Upload Image with Jquery Ajax and PHP</h2>				
		<form id="posts" name="posts" method="post">
			<textarea name="message" id="message"></textarea><br>				
		</form>		
	</div>	
</div>
<script src="tinymce/tinymce.min.js"></script>
<script>
tinymce.init({
	selector: "textarea",
	plugins: "code",
	toolbar: "undo redo | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link code image_upload",
	menubar:false,
    statusbar: false,
	content_style: ".mce-content-body {font-size:15px;font-family:Arial,sans-serif;}",
	height: 400,
	setup: function(ed) {
		
		var fileInput = $('<input id="tinymce-uploader" type="file" name="pic" accept="image/*" style="display:none">');
		$(ed.getElement()).parent().append(fileInput);
		
		fileInput.on("change",function(){			
			var file = this.files[0];
			var reader = new FileReader();			
			var formData = new FormData();
			var files = file;
			formData.append("file",files);
			formData.append('filetype', 'image');				
			jQuery.ajax({
				url: "tinymce_upload.php",
				type: "post",
				data: formData,
				contentType: false,
				processData: false,
				async: false,
				success: function(response){
					var fileName = response;
					if(fileName) {
						ed.insertContent('<img src="upload/'+fileName+'"/>');
					}
				}
			});		
			reader.readAsDataURL(file);	 
		});		
		
		ed.addButton('image_upload', {
			tooltip: 'Upload Image',
			icon: 'image',
			onclick: function () {
				fileInput.trigger('click');
			}
		});
	}
});
</script>
</body>
</html>
tinymce_upload.php
//tinymce_upload.php
<?php
$fileName = $_FILES['file']['name'];
$fileType = $_POST['filetype'];
if($fileType == 'image'){
  $validExtension = array('png','jpeg','jpg');
}
$uploadDir = "upload/".$fileName;
$fileExtension = pathinfo($uploadDir, PATHINFO_EXTENSION);
$fileExtension = strtolower($fileExtension);
if(in_array($fileExtension, $validExtension)){
   if(move_uploaded_file($_FILES['file']['tmp_name'],$uploadDir)){ 
    echo $fileName;
  }
}
?>

Sunday, December 20, 2020

Python Flask Delete image unlink files from folder and records from the database MySQLdb

Python Flask Delete image unlink files from folder and records from the database MySQLdb

app.py
 
#app.py
from flask import Flask, render_template, jsonify, request
from flask_mysqldb import MySQL,MySQLdb #pip install flask-mysqldb https://github.com/alexferl/flask-mysqldb
import os

app = Flask(__name__)
    
app.secret_key = "caircocoders-ednalan-2020"
    
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)

UPLOAD_FOLDER = 'static/uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

@app.route('/')
def main():
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    result = cur.execute("SELECT * FROM uploads ORDER BY id")
    gallery = cur.fetchall()
    return render_template('delete.html', gallery=gallery)
 
@app.route('/delete/')
def delete(get_ig):
    cursor = mysql.connection.cursor()
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    result = cur.execute("SELECT * FROM uploads WHERE id = %s", [get_ig])
    data = cur.fetchone()
    filename = data['file_name']
	
    os.unlink(os.path.join(app.config['UPLOAD_FOLDER'], filename))
    cur.execute('DELETE FROM uploads WHERE id = {0}'.format(get_ig))
    mysql.connection.commit()
    cur.close()
    print('File successfully deleted!')
    msg = 'Success deleted'		
    return jsonify(msg)
	
if __name__ == '__main__':
    app.run(debug=True)
templates/delete.html
//templates/delete.html
<html>  
 <head>  
  <title>Python Flask Delete image unlink files from folder and records from the database MySQLdb </title> 
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>  
 </head>  
 <body> 
<div class="container">
	<div class="row">
	<div class="col-md-12">
        <h4>Python Flask Delete image unlink files from folder and records from the database MySQLdb </h4>
        <div class="table-responsive">
		<table id="mytable" class="table table-bordred table-striped">
            <thead>
                <th>Photo</th>
                <th>Delete</th>
            </thead>
		<tbody>
		{% for row in gallery %}
		<tr>
		<td><img src="static/uploads/{{row.file_name}}" width="60"/></td>
		<td><p><a href="/delete/{{row.id}}" class="btn btn-danger btn-xs"><span class="glyphicon glyphicon-trash"></span></a></p></td>
		</tr>
		{% endfor %}
		</tbody>   
		</table> 
        </div>
        </div>
	</div>
</div>
 </body>  
</html>   

Thursday, December 17, 2020

jQuery Ajax Drag and Drop File Upload with Python Flask and MySQLdb


jQuery Ajax Drag and Drop File Upload with Python Flask and MySQLdb

In this tutorial you will learn how to implement drag and drop file upload using jQuery and Python Flask. 
We will use DropzoneJS jQuery plugin to handle drag and drop file upload functionality.

DropzoneJS is an open source library that provides drag’n’drop file uploads with image previews.

It’s lightweight, doesn’t depend on any other library (like jQuery) and is highly customizable.

www.dropzonejs.com
Download https://github.com/enyo/dropzone/archive/v5.7.0.zip

Create Database

CREATE TABLE `uploads` (
  `id` int(11) NOT NULL,
  `file_name` varchar(150) NOT NULL,
  `upload_time` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
app.py
 
#app.py
from flask import Flask, render_template, jsonify, request
from flask_mysqldb import MySQL,MySQLdb #pip install flask-mysqldb https://github.com/alexferl/flask-mysqldb
from werkzeug.utils import secure_filename
import os
#import magic
import urllib.request
from datetime import datetime

app = Flask(__name__)
   
app.secret_key = "caircocoders-ednalan-2020"
   
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)
   
UPLOAD_FOLDER = 'static/uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
 
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
 
def allowed_file(filename):
 return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
 
@app.route('/')
def main():
    return render_template('drop_and_drop_upload.html')
     
@app.route("/upload",methods=["POST","GET"])
def upload():
    cursor = mysql.connection.cursor()
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)	
    if request.method == 'POST':
        file = request.files['file']
        filename = secure_filename(file.filename)
        now = datetime.now()
		
        if file and allowed_file(file.filename):
           file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

           cur.execute("INSERT INTO uploads (file_name, upload_time) VALUES (%s, %s)",[file.filename, now])
           mysql.connection.commit()
           cur.close()
           print('File successfully uploaded ' + file.filename + ' to the database!')
        else:
           print('Invalid Uplaod only txt, pdf, png, jpg, jpeg, gif') 
        msg = 'Success Uplaod'		
    return jsonify(msg)
	
if __name__ == '__main__':
    app.run(debug=True)
templates/drop_and_drop_upload.html
//templates/drop_and_drop_upload.html
<html>  
 <head>  
  <title>jQuery Ajax Drag and Drop File Upload with Python Flask and MySQLdb</title>  
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="/static/dropzone/dropzone.css" />
<script type="text/javascript" src="/static/dropzone/dropzone.js"></script>
 </head>  
 <body> 
<div class="container"> 
	<h2>jQuery Ajax Drag and Drop File Upload with Python Flask and MySQLdb</h2>
	<div class="dropzone">
		<div class="dz-message needsclick">
			<h1>Drop files here or click to upload.</h1>
		</div>
	</div>
</div>
<script>
$(document).ready(function(){
	$(".dropzone").dropzone({
	  url: '/upload',
	  width: 300,
	  height: 300, 
	  progressBarWidth: '100%',
	  maxFileSize: '5MB'
	})
});
</script>	
 </body>  
</html>   

jQuery Ajax Drag and Drop File Upload with PHP and MySQLi

jQuery Ajax Drag and Drop File Upload with PHP and MySQLi

In this tutorial you will learn how to implement drag and drop file upload using jQuery and PHP. 
We will use DropzoneJS jQuery plugin to handle drag and drop file upload functionality.

DropzoneJS is an open source library that provides drag’n’drop file uploads with image previews.

It’s lightweight, doesn’t depend on any other library (like jQuery) and is highly customizable.

www.dropzonejs.com

Create Database

CREATE TABLE `uploads` (
  `id` int(11) NOT NULL,
  `file_name` varchar(150) NOT NULL,
  `upload_time` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

drag_and_drop_upload.php
//drag_and_drop_upload.php
<html>  
 <head>  
  <title>jQuery Ajax Drag and Drop File Upload with PHP and MySQLi</title>  
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="dropzone/dropzone.css" />
<script type="text/javascript" src="dropzone/dropzone.js"></script>
<script type="text/javascript" src="js/upload.js"></script>
 </head>  
 <body> 
<div class="container"> 
	<h2>jQuery Ajax Drag and Drop File Upload with PHP and MySQLi</h2>
	<div class="dropzone">
		<div class="dz-message needsclick">
			<h1>Drop files here or click to upload.</h1>
		</div>
	</div>
</div>
<script>
$(document).ready(function(){
	$(".dropzone").dropzone({
	  url: 'upload.php',
	  width: 300,
	  height: 300, 
	  progressBarWidth: '100%',
	  maxFileSize: '5MB'
	})
});
</script>	
 </body>  
</html>   
upload.php
//upload.php
<?php 
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testingdb";
$conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}
if(!empty($_FILES)){     
    $uploadDir = "upload/";
    $fileName = $_FILES['file']['name'];
    $uploadedFile = $uploadDir.$fileName;    
    if(move_uploaded_file($_FILES['file']['tmp_name'],$uploadedFile)) {
        $mysqlInsert = "INSERT INTO uploads (file_name, upload_time)VALUES('".$fileName."','".date("Y-m-d H:i:s")."')";
		mysqli_query($conn, $mysqlInsert);
    }   
}
?>

Monday, December 7, 2020

How to install node.js on windows 10 and run first node.js hello program

How to install node.js on windows 10 and run first node.js hello program

Node.js is an open source framework that allows us to run JavaScript on the server. The Node.js is very memory efficient as it runs as single-threaded, non-blocking and asynchronously. It supports all major platform like Windows, Linux, Unix, Mac etc. Due to Node.js awesome features, it becomes popular among web developers to develop dynamic web projects.

Related Post