article

Wednesday, January 13, 2021

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>

Related Post