article

Saturday, February 6, 2021

Jquery Fullcalandar CRUD(Create, Read, Update, Delete) with Python Flask Jquery Ajax and Mysql

Jquery Fullcalandar CRUD(Create, Read, Update, Delete) with Python Flask Jquery Ajax and Mysql

This tutorial is a Jquery Fullcalandar Integration FullCalendar.js plugin https://fullcalendar.io/demos

--
-- Table structure for table `events`
--

CREATE TABLE `events` (
  `id` int(11) NOT NULL,
  `title` varchar(255) NOT NULL,
  `start_event` datetime NOT NULL,
  `end_event` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `events`
--

INSERT INTO `events` (`id`, `title`, `start_event`, `end_event`) VALUES
(1, 'Python Flask coding visual studio', '2021-02-03 16:00:00', '2021-02-04 03:00:00'),
(2, 'PHP coding Notepad++', '2021-02-08 03:17:15', '2021-02-10 04:00:00'),
(6, 'Basketball', '2021-02-05 00:00:00', '2021-02-05 14:30:00'),
(7, 'Birthday Party', '2021-02-12 00:00:00', '2021-02-13 00:00:00');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `events`
--
ALTER TABLE `events`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `events`
--
ALTER TABLE `events`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;
app.py
#app.py
from flask import Flask, render_template, request, 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():
    cursor = mysql.connection.cursor()
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    cur.execute("SELECT * FROM events ORDER BY id")
    calendar = cur.fetchall()  
    return render_template('index.html', calendar = calendar)

@app.route("/insert",methods=["POST","GET"])
def insert():
    cursor = mysql.connection.cursor()
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    if request.method == 'POST':
        title = request.form['title']
        start = request.form['start']
        end = request.form['end']
        print(title)     
        print(start)  
        cur.execute("INSERT INTO events (title,start_event,end_event) VALUES (%s,%s,%s)",[title,start,end])
        mysql.connection.commit()       
        cur.close()
        msg = 'success'   
    return jsonify(msg)

@app.route("/update",methods=["POST","GET"])
def update():
    cursor = mysql.connection.cursor()
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    if request.method == 'POST':
        title = request.form['title']
        start = request.form['start']
        end = request.form['end']
        id = request.form['id']
        print(title)     
        print(start)  
        cur.execute("UPDATE events SET title = %s, start_event = %s, end_event = %s WHERE id = %s ", [title, start, end, id])
        mysql.connection.commit()       
        cur.close()
        msg = 'success'   
    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['id']
        print(getid)
        cur.execute('DELETE FROM events WHERE id = {0}'.format(getid))
        mysql.connection.commit()       
        cur.close()
        msg = 'Record deleted successfully'   
    return jsonify(msg) 

if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html>
 <head>
  <title>Jquery Fullcalandar CRUD(Create, Read, Update, Delete) with Python Flask and Mysql</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.css" />
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.min.js"></script>
  <script>
  $(document).ready(function() {
   var calendar = $('#calendar').fullCalendar({
    editable:true,
    header:{
     left:'prev,next today',
     center:'title',
     right:'month,agendaWeek,agendaDay'
    },
    events: [{% for row in calendar %}{ id : '{{row.id}}', title : '{{row.title}}', start : '{{row.start_event}}', end : '{{row.end_event}}', }, {% endfor %}],
    selectable:true,
    selectHelper:true,
    select: function(start, end, allDay)
    {
     var title = prompt("Enter Event Title");
     if(title)
     {
      var start = $.fullCalendar.formatDate(start, "Y-MM-DD HH:mm:ss");
      var end = $.fullCalendar.formatDate(end, "Y-MM-DD HH:mm:ss");
      $.ajax({
       url:"/insert",
       type:"POST",
       data:{title:title, start:start, end:end},
       success:function(data)
       {
         //alert(data)
        alert("Added Successfully");
        window.location.replace("/");
       }
      })
     }
    },
    editable:true,
    eventResize:function(event)
    {
     var start = $.fullCalendar.formatDate(event.start, "Y-MM-DD HH:mm:ss");
     var end = $.fullCalendar.formatDate(event.end, "Y-MM-DD HH:mm:ss");
     var title = event.title;
     var id = event.id;
     $.ajax({
      url:"/update",
      type:"POST",
      data:{title:title, start:start, end:end, id:id},
      success:function(){
       calendar.fullCalendar('refetchEvents');
       alert('Event Update');
      }
     })
    },
    
    eventDrop:function(event)
    {
     var start = $.fullCalendar.formatDate(event.start, "Y-MM-DD HH:mm:ss");
     var end = $.fullCalendar.formatDate(event.end, "Y-MM-DD HH:mm:ss");
     var title = event.title;
     var id = event.id;
     $.ajax({
      url:"/update",
      type:"POST",
      data:{title:title, start:start, end:end, id:id},
      success:function()
      {
       calendar.fullCalendar('refetchEvents');
       alert("Event Updated");
      }
     });
    },

    eventClick:function(event)
    {
     if(confirm("Are you sure you want to remove it?"))
     {
      var id = event.id;
      $.ajax({
       url:"/ajax_delete",
       type:"POST",
       data:{id:id},
       success:function()
       {
        calendar.fullCalendar('refetchEvents');
        alert("Event Removed");
       }
      })
     }
    },

   });
  });
   
  </script>
 </head>
 <body>
  <br />
  <h2 align="center"><a href="#">Jquery Fullcalandar CRUD(Create, Read, Update, Delete) with Python Flask Jquery Ajax and Mysql</a></h2>
  <br />
  <div class="container">
   <div id="calendar"></div>
  </div>
 </body>
</html>

Wednesday, February 3, 2021

Insert Bootstrap Tokenfield Tag Data using PHP Mysql and Jquery Ajax

Insert Bootstrap Tokenfield Tag Data using PHP Mysql and Jquery Ajax

--
-- Table structure for table `skills`
--

CREATE TABLE `skills` (
  `id` int(11) NOT NULL,
  `skillname` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `skills`
--

INSERT INTO `skills` (`id`, `skillname`) VALUES
(2, 'Python Flask'),
(3, 'Laravel'),
(4, 'Python Django'),
(5, 'Angular'),
(6, 'PHP'),
(7, 'Codeigniter'),
(8, 'Python TKinter'),
(9, 'JQuery'),
(10, 'Javascript'),
(11, 'CakePHP'),
(12, 'Mysql'),
(13, 'MongoDB'),
(14, 'Java'),
(15, 'Android Studio'),
(16, 'Bootstrap'),
(17, 'Java Swing'),
(18, 'NodeJS'),
(19, 'NodeJS Express');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `skills`
--
ALTER TABLE `skills`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `skills`
--
ALTER TABLE `skills`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=20;
--
-- Table structure for table `user`
--

CREATE TABLE `user` (
  `id` int(11) NOT NULL,
  `fullname` varchar(150) NOT NULL,
  `skills` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `user`
--

INSERT INTO `user` (`id`, `fullname`, `skills`) VALUES
(1, 'Michael00000', 'Holz0000'),
(2, 'Paula', 'Wilson'),
(3, 'Antonio11111', 'Moreno11111'),
(4, 'cairocoders', 'NodeJS, NodeJS Express, CakePHP, Python Django');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `user`
--
ALTER TABLE `user`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `user`
--
ALTER TABLE `user`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;

JqueryUI Autocomplete : https://jqueryui.com/autocomplete/
Bootstrap Tokenfield : https://sliptree.github.io/bootstrap-tokenfield/
index.php
//index.php
<!DOCTYPE html>
<html>
 <head>
  <title>Insert Bootstrap Tokenfield Tag Data using PHP Mysql and Jquery Ajax</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-tokenfield/0.12.0/css/bootstrap-tokenfield.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-tokenfield/0.12.0/bootstrap-tokenfield.js"></script>
</head>
 <body>
  <br />
  <div class="container">
   <div class="row">
    <h2 align="center">Insert Bootstrap Tokenfield Tag Data using PHP Mysql and Jquery Ajax</h2>
    <div class="col-md-6" style="margin:0 auto; float:none;">
      <p id="success_message"></p>
      <form method="post" id="reg_form">
       <div class="form-group">
        <label>Enter Name</label>
        <input type="text" name="name" id="name" class="form-control" />
       </div>
       <div class="form-group">
        <label>Enter your Skill</label>
        <input type="text" name="skill" id="skill" class="form-control" />
       </div>
       <div class="form-group">
        <input type="submit" name="submit" id="submit" class="btn btn-info" value="Submit" />
       </div>
      </form>
     </div>
    </div>
  </div> 
<?php
 include('dbcon.php');
$result = $conn->query("SELECT * FROM skills");
$result->fetch_all(MYSQLI_ASSOC);
?>
  <script>
    $(document).ready(function(){
      $('#skill').tokenfield({
        autocomplete:{
        source: [<?php foreach($result as $row) { ?>
			"<?php echo $row['skillname']; ?>", 
			<?php } ?>],
        delay:100
        },
        showAutocompleteOnFocus: true
      });
     
      $('#reg_form').on('submit', function(event){
        event.preventDefault();
        if($.trim($('#name').val()).length == 0) {
          alert("Please Enter Your Name");
          return false;
        }else if($.trim($('#skill').val()).length == 0) {
          alert("Please Enter Atleast one Skill");
          return false;
        }else{
          var form_data = $(this).serialize();
          $('#submit').attr("disabled","disabled");
          $.ajax({
              url:"insert.php",
              method:"POST",
              data:form_data,
              beforeSend:function(){
              $('#submit').val('Submitting...');
              },
              success:function(data){
                if(data != '') {
                  $('#name').val('');
                  $('#skill').tokenfield('setTokens',[]);
                  $('#success_message').html(data);
                  $('#submit').attr("disabled", false);
                  $('#submit').val('Submit');
                }
              }
          });
          setInterval(function(){
            $('#success_message').html('');
          }, 5000);
        }
      });
});
</script>     
</body>
</html>
insert.php
//insert.php
<?php
include('dbcon.php');
if(isset($_POST["name"]))
{
	$fullname = $_POST["name"];
	$skills = $_POST["skill"];
	$sql = "INSERT INTO user(fullname,skills) VALUES ('$fullname','$skills')"; 
    $insert = $conn->query($sql);
	$output = '
	  <div class="alert alert-success">
	   Your data has been successfully saved 
	  </div>
	  ';
	echo $output;
}
?>

Python Flask Insert Bootstrap Tokenfield Tag Data using Jquery Ajax and Mysql database

Python Flask Insert Bootstrap Tokenfield Tag Data using Jquery Ajax and Mysql database

--
-- Table structure for table `skills`
--

CREATE TABLE `skills` (
  `id` int(11) NOT NULL,
  `skillname` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `skills`
--

INSERT INTO `skills` (`id`, `skillname`) VALUES
(2, 'Python Flask'),
(3, 'Laravel'),
(4, 'Python Django'),
(5, 'Angular'),
(6, 'PHP'),
(7, 'Codeigniter'),
(8, 'Python TKinter'),
(9, 'JQuery'),
(10, 'Javascript'),
(11, 'CakePHP'),
(12, 'Mysql'),
(13, 'MongoDB'),
(14, 'Java'),
(15, 'Android Studio'),
(16, 'Bootstrap'),
(17, 'Java Swing'),
(18, 'NodeJS'),
(19, 'NodeJS Express');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `skills`
--
ALTER TABLE `skills`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `skills`
--
ALTER TABLE `skills`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=20;

--
-- Table structure for table `user`
--

CREATE TABLE `user` (
  `id` int(11) NOT NULL,
  `fullname` varchar(150) NOT NULL,
  `skills` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `user`
--

INSERT INTO `user` (`id`, `fullname`, `skills`) VALUES
(1, 'Michael00000', 'Holz0000'),
(2, 'Paula', 'Wilson'),
(3, 'Antonio11111', 'Moreno11111'),
(4, 'cairocoders', 'NodeJS, NodeJS Express, CakePHP, Python Django');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `user`
--
ALTER TABLE `user`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `user`
--
ALTER TABLE `user`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;

JqueryUI Autocomplete : https://jqueryui.com/autocomplete/
Bootstrap Tokenfield : https://sliptree.github.io/bootstrap-tokenfield/

app.py
#app.py
from flask import Flask, render_template, request, 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():
    cursor = mysql.connection.cursor()
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    cur.execute("SELECT * FROM skills ORDER BY id desc")
    skills = cur.fetchall() 
    return render_template('index.html', skills=skills)

@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':
        name = request.form['name']
        skill = request.form['skill']
        print(name)     
        print(skill)  
        cur.execute("INSERT INTO user (fullname,skills) VALUES (%s,%s)",[name,skill])
        mysql.connection.commit()       
        cur.close()
        msg = 'New record created successfully'   
    return jsonify(msg)

if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html>
 <head>
  <title>Python Flask Insert Bootstrap Tokenfield Tag Data using Jquery Ajax and Mysql database</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  
  <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css">
  <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-tokenfield/0.12.0/css/bootstrap-tokenfield.min.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-tokenfield/0.12.0/bootstrap-tokenfield.js"></script>
 </head>
 <body>
  <br />
  <div class="container">
   <div class="row">
    <h2 align="center">Python Flask Insert Bootstrap Tokenfield Tag Data using Jquery Ajax and Mysql database</h2>
     <br />
     <div class="col-md-6" style="margin:0 auto; float:none;">
      <span id="success_message"></span>
      <form method="post" id="reg_form">
       <div class="form-group">
        <label>Enter Name</label>
        <input type="text" name="name" id="name" class="form-control" />
       </div>
       <div class="form-group">
        <label>Enter your Skill</label>
        <input type="text" name="skill" id="skill" class="form-control" />
       </div>
       <div class="form-group">
        <input type="submit" name="submit" id="submit" class="btn btn-info" value="Submit" />
       </div>
      </form>
     </div>
    </div>
   </div>
  </div>
<script>
$(document).ready(function(){
  $('#skill').tokenfield({
    autocomplete:{
    source: [{% for row in skills %} '{{row.skillname}}', {% endfor %}],
    delay:100
    },
    showAutocompleteOnFocus: true
  });

  $('#reg_form').on('submit', function(event){
    event.preventDefault();
    if($.trim($('#name').val()).length == 0) {
      alert("Please Enter Your Name");
      return false;
    }else if($.trim($('#skill').val()).length == 0) {
      alert("Please Enter Atleast one Skill");
      return false;
    }else{
        var form_data = $(this).serialize();
        $('#submit').attr("disabled","disabled");
        $.ajax({
            url:"/ajax_add",
            method:"POST",
            data:form_data,
            beforeSend:function(){
            $('#submit').val('Submitting...');
            },
            success:function(data){
              if(data != '') {
                $('#name').val('');
                $('#skill').tokenfield('setTokens',[]);
                $('#success_message').html(data);
                $('#submit').attr("disabled", false);
                $('#submit').val('Submit');
              }
            }
        });
        setInterval(function(){
          $('#success_message').html('');
        }, 5000);
    }
  });
 
});
</script>  
</body>
</html>

Tuesday, February 2, 2021

PHP Mysqli Multiple Select option using Bootstrap Select Plugin and Jquery Ajax

PHP Mysqli Multiple Select option using Bootstrap Select Plugin and Jquery Ajax

--
-- Table structure for table `skills`
--

CREATE TABLE `skills` (
  `id` int(11) NOT NULL,
  `skillname` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `skills`
--
ALTER TABLE `skills`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `skills`
--
ALTER TABLE `skills`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;

bootstrap select https://developer.snapappointments.com/bootstrap-select/examples/
//index.html
<!DOCTYPE html>
<html>
 <head>
  <title>PHP Mysqli Multiple Select option using Bootstrap Select Plugin and Jquery Ajax</title>
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/css/bootstrap-select.min.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/js/bootstrap-select.min.js"></script>
 </head>
 <body>
  <br /><br />
  <div class="container">
   <br />
   <h2 align="center">PHP Mysqli Multiple Select option using Bootstrap Select Plugin and Jquery Ajax</h2>
   <br />
   <div class="col-md-4" style="margin-left:200px;">
    <form method="post" id="multiple_select_form">
     <select name="skills" id="skills" class="form-control selectpicker" data-live-search="true" multiple>
      <option value="Python Flask">Python Flask</option>
      <option value="Python Django">Python Django</option>
      <option value="Express.js">Express.js</option>
      <option value="Laravel">Laravel</option>
      <option value="Spring">Spring</option>
      <option value="Angular">Angular</option>
      <option value="React">React</option>
     </select>
     <br /><br />
     <input type="hidden" name="hidden_skills" id="hidden_skills" />
     <input type="submit" name="submit" class="btn btn-info" value="Submit" />
    </form>
    <br />
   </div>
  </div>
  <script>
    $(document).ready(function(){
     $('.selectpicker').selectpicker();
    
     $('#skills').change(function(){
      $('#hidden_skills').val($('#skills').val());
     });
    
     $('#multiple_select_form').on('submit', function(event){
      event.preventDefault();
      if($('#skills').val() != '')
      {
       var form_data = $(this).serialize();
       $.ajax({
        url:"insert.php",
        method:"POST",
        data:form_data,
        success:function(data)
        {
         //console.log(data);
         $('#hidden_skills').val('');
         $('.selectpicker').selectpicker('val', '');
         alert(data);
        }
       })
      }
      else
      {
       alert("Please select framework");
       return false;
      }
     });
    });
    </script>
 </body>
</html>
insert.php
//insert.php
<?php
$connect = mysqli_connect("localhost", "root", "", "testingdb");
$query = "INSERT INTO skills(skillname) VALUES ('".$_POST["hidden_skills"]."')";
if(mysqli_query($connect, $query))
{
 echo 'Data Inserted';
}
?>

Monday, February 1, 2021

Python Flask Multiple Select option using Bootstrap Select Plugin and Jquery Ajax Mysqli database

Python Flask Multiple Select option using Bootstrap Select Plugin and Jquery Ajax Mysqli database

--
-- Table structure for table `skills`
--

CREATE TABLE `skills` (
  `id` int(11) NOT NULL,
  `skillname` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `skills`
--
ALTER TABLE `skills`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `skills`
--
ALTER TABLE `skills`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;

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

from flask_mysqldb import MySQL,MySQLdb #pip install flask-mysqldb https://github.com/alexferl/flask-mysqldb
app.py
 
#app.py
from flask import Flask, render_template, request, 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(): 
    return render_template('index.html')

@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':
        hidden_skills = request.form['hidden_skills']
        print(hidden_skills)     
        cur.execute("INSERT INTO skills (skillname) VALUES (%s)",[hidden_skills])
        mysql.connection.commit()       
        cur.close()
        msg = 'New record created successfully'   
    return jsonify(msg)

if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html>
 <head>
  <title>Python Flask Multiple Select option using Bootstrap Select Plugin and Jquery Ajax Mysqli database</title>
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/css/bootstrap-select.min.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/js/bootstrap-select.min.js"></script>
 </head>
 <body>
  <br /><br />
  <div class="container">
   <br />
   <h2 align="center">Python Flask Multiple Select option using Bootstrap Select Plugin and Jquery Ajax Mysqli database</h2>
   <br />
   <div class="col-md-4" style="margin-left:200px;">
    <form method="post" id="multiple_select_form">
     <select name="skills" id="skills" class="form-control selectpicker" data-live-search="true" multiple>
      <option value="Python Flask">Python Flask</option>
      <option value="Python Django">Python Django</option>
      <option value="Express.js">Express.js</option>
      <option value="Laravel">Laravel</option>
      <option value="Spring">Spring</option>
      <option value="Angular">Angular</option>
      <option value="React">React</option>
     </select>
     <br /><br />
     <input type="hidden" name="hidden_skills" id="hidden_skills" />
     <input type="submit" name="submit" class="btn btn-info" value="Submit" />
    </form>
    <br />
   </div>
  </div>
  <script>
    $(document).ready(function(){
     $('.selectpicker').selectpicker();
    
     $('#skills').change(function(){
      $('#hidden_skills').val($('#skills').val());
     });
    
     $('#multiple_select_form').on('submit', function(event){
      event.preventDefault();
      if($('#skills').val() != '')
      {
       var form_data = $(this).serialize();
       $.ajax({
        url:"/ajax_add",
        method:"POST",
        data:form_data,
        success:function(data)
        {
         //console.log(data);
         $('#hidden_skills').val('');
         $('.selectpicker').selectpicker('val', '');
         alert(data);
        }
       })
      }
      else
      {
       alert("Please select framework");
       return false;
      }
     });
    });
    </script>
 </body>
</html>

Wednesday, January 27, 2021

PHP Mysqli Login Form Using Bootstrap Modal with Ajax Jquery

PHP Mysqli Login Form Using Bootstrap Modal with Ajax Jquery

--
-- Table structure for table `admin_login`
--

CREATE TABLE `admin_login` (
  `admin_id` int(11) NOT NULL,
  `admin_name` varchar(250) NOT NULL,
  `admin_password` varchar(250) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Dumping data for table `admin_login`
--

INSERT INTO `admin_login` (`admin_id`, `admin_name`, `admin_password`) VALUES
(1, 'admin', 'admin');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `admin_login`
--
ALTER TABLE `admin_login`
  ADD PRIMARY KEY (`admin_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `admin_login`
--
ALTER TABLE `admin_login`
  MODIFY `admin_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
index.ph
 //index.php
 <!DOCTYPE html>  
<html>  
<head>  
<title>PHP Mysqli Login Form Using Bootstrap Modal with Ajax Jquery</title>  
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>  
<body>  
           <br />  
           <div class="container" style="width:700px;">  
                <h3 align="center">PHP Mysqli Login Form Using Bootstrap Modal with Ajax Jquery</h3><br />  
                <br />  
                <br />  
                <br />  
                <br />  
                <br />  
<?php   
 session_start();  
   
                if(isset($_SESSION['username']))  
                {  
                ?>  
                <div align="center">  
                     <h1>Welcome - <?php echo $_SESSION['username']; ?></h1><br />  
                     <a href="#" id="logout">Logout</a>  
                </div>  
                <?php  
                }  
                else  
                {  
                ?>  
                <div align="center">  
                     <a data-target="#myModal" role="button" class="btn btn-warning" data-toggle="modal"><span class="glyphicon glyphicon-hand-up"></span>Login</a>
                </div>  
                <?php  
                }  
                ?>  
           </div>  
           <br />  
		   	
 <div id="myModal" class="modal fade">  
      <div class="modal-dialog">  
   <!-- Modal content-->  
           <div class="modal-content">  
                <div class="modal-header">  
                     <button type="button" class="close" data-dismiss="modal">×</button>  
                     <h4 class="modal-title">PHP Mysqli Login Form Using Bootstrap Modal with Ajax Jquery</h4>  
                </div>  
                <div class="modal-body">  
                     <label>Username</label>  
                     <input type="text" name="username" id="username" class="form-control" />  
                     <br />  
                     <label>Password</label>  
                     <input type="password" name="password" id="password" class="form-control" />  
                     <br />  
                     <button type="button" name="login_button" id="login_button" class="btn btn-warning">Login</button>  
                </div>  
           </div>  
      </div>  
 </div>  
 <script>  
 $(document).ready(function(){  
      $('#login_button').click(function(){  
           var username = $('#username').val();  
           var password = $('#password').val();  
           if(username != '' && password != '')  
           {  
                $.ajax({  
                     url:"action.php",  
                     method:"POST",  
                     data: {username:username, password:password},  
                     success:function(data)  
                     {  
                          //alert(data);  
                          if(data == 'No')  
                          {  
                               alert("Wrong Data");  
                          }  
                          else  
                          {  
                               $('#loginModal').hide();  
                               location.reload();  
                          }  
                     }  
                });  
           }  
           else  
           {  
                alert("Both Fields are required");  
           }  
      });  
      $('#logout').click(function(){  
           var action = "logout";  
           $.ajax({  
                url:"action.php",  
                method:"POST",  
                data:{action:action},  
                success:function()  
                {  
                     location.reload();  
                }  
           });  
      });  
 });  
 </script> 
		   
      </body>  
 </html>  
action.php
//action.php
<?php  
 session_start();  
 $connect = mysqli_connect("localhost", "root", "", "testingdb");  
 if(isset($_POST["username"]))  
 {  
      $query = "  
      SELECT * FROM admin_login  
      WHERE admin_name = '".$_POST["username"]."'  
      AND admin_password = '".$_POST["password"]."'  
      ";  
      $result = mysqli_query($connect, $query);  
      if(mysqli_num_rows($result) > 0)  
      {  
           $_SESSION['username'] = $_POST['username'];  
           echo 'Success';  
      }  
      else  
      {  
           echo 'No';  
      }  
 }  
 if(isset($_POST["action"]))  
 {  
      unset($_SESSION["username"]);  
 }  
 ?>
 

Tuesday, January 26, 2021

Python Flask Login Form Using Bootstrap Modal with Ajax Jquery password hash and session

Python Flask Login Form Using Bootstrap Modal with Ajax Jquery password hash and session

--
-- Table structure for table `admin_login`
--

CREATE TABLE `admin_login` (
  `admin_id` int(11) NOT NULL,
  `admin_name` varchar(250) NOT NULL,
  `admin_password` varchar(250) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Dumping data for table `admin_login`
--

INSERT INTO `admin_login` (`admin_id`, `admin_name`, `admin_password`) VALUES
(1, 'admin', 'pbkdf2:sha256:150000$FXLDgm3a$bd46f6b7b44124a523f9566d03bf110ba2ebf28bfd3522faeddd56eabebcb7f5');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `admin_login`
--
ALTER TABLE `admin_login`
  ADD PRIMARY KEY (`admin_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `admin_login`
--
ALTER TABLE `admin_login`
  MODIFY `admin_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;

app.py
#app.py
from flask import Flask, render_template, request, jsonify, flash, redirect, session
from flask_mysqldb import MySQL,MySQLdb #pip install flask-mysqldb https://github.com/alexferl/flask-mysqldb
from werkzeug.security import generate_password_hash, check_password_hash

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():
    hash = generate_password_hash('cairocoders')
    check_hash = check_password_hash(hash, 'cairocoders')   
    return render_template('index.html', hash=hash, check_hash=check_hash)

@app.route("/action",methods=["POST","GET"])
def action(): 
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor) 
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        print(username)
        print(password)
        result = cur.execute("SELECT * FROM admin_login WHERE admin_name = %s ", [username])
        print(result)
        if result > 0:
            data = cur.fetchone()
            rs_password = data['admin_password']
            print(rs_password)
            if check_password_hash(rs_password, password):
                session['logged_in'] = True
                session['username'] = username
                msg = 'success'
            else:
               msg = 'No-data'
        else:
            msg = 'No-data'    
    return jsonify(msg)   

@app.route('/logout')
def logout():
    session.clear()
    return redirect('/')

if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>  
 <html>  
<head>  
<title>Python Flask Login Form Using Bootstrap Modal with Ajax Jquery password hash and session</title>  
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>  
<body>  
<div class="container" style="width:700px;">  
                <h3 align="center">Python Flask Login Form Using Bootstrap Modal with Ajax Jquery password hash and session</h3><br />  
                <br />  
                <br />  
                <!--<p>hash : {{ hash }}</p>
                <p>hash : {{ check_hash }}</p> -->
                <br />  
                <br />  
                <br />  
                {% if session.logged_in %}
                <div align="center">  
                     <h1>Welcome - {{session.username}}</h1><br />  
                     <a href="/logout">Logout</a>  
                </div>  
                {% else %}  
                <div align="center">  
                     <a data-target="#myModal" role="button" class="btn btn-warning" data-toggle="modal"><span class="glyphicon glyphicon-hand-up"></span>Login</a>
                </div>  
                {% endif %} 
           </div>  
           <br />  
		   	
 <div id="myModal" class="modal fade">  
      <div class="modal-dialog">  
   <!-- Modal content-->  
           <div class="modal-content">  
                <div class="modal-header">  
                     <button type="button" class="close" data-dismiss="modal">×</button>  
                     <h4 class="modal-title">Python Flask Login Form Using Bootstrap Modal with Ajax Jquery password hash and session</h4>  
                </div>  
                <div class="modal-body">  
                     <label>Username</label>  
                     <input type="text" name="username" id="username" class="form-control" />  
                     <br />  
                     <label>Password</label>  
                     <input type="password" name="password" id="password" class="form-control" />  
                     <br />  
                     <button type="button" name="login_button" id="login_button" class="btn btn-warning">Login</button>  
                </div>  
           </div>  
      </div>  
 </div>  
 <script>  
 $(document).ready(function(){  
      $('#login_button').click(function(){  
           var username = $('#username').val();  
           var password = $('#password').val();  
           if(username != '' && password != '')  
           {  
                $.ajax({  
                     url:"/action",  
                     method:"POST",  
                     data: {username:username, password:password},  
                     success:function(data)  
                     {  
                          alert(data);  
                          if(data == 'No-data')  
                          {  
                               alert("Invalid Email Or Password!");  
                          }  
                          else  
                          {  
                               $('#loginModal').hide();  
                               location.reload();  
                          }  
                     }  
                });  
           }  
           else  
           {  
                alert("Both Fields are required");  
           }  
      });    
 });  
 </script>   
      </body>  
 </html>  

Sunday, January 24, 2021

PHP MySQL Date Range Search with jQuery Ajax DatePicker

PHP MySQL Date Range Search with jQuery Ajax DatePicker

jQuery UI is a curated set of user interface interactions, effects, widgets, and themes built on top of the jQuery JavaScript Library. Whether you're building highly interactive web applications or you just need to add a date picker to a form control, jQuery UI is the perfect choice.


The datepicker is tied to a standard form input field. Focus on the input (click, or use the tab key) to open an interactive calendar in a small overlay. Choose a date, click elsewhere on the page (blur the input), or hit the Esc key to close. If a date is chosen, feedback is shown as the input's value.
--
-- Table structure for table `orders`
--

CREATE TABLE `orders` (
  `id` int(11) NOT NULL,
  `customer_name` varchar(100) NOT NULL,
  `purchased_items` varchar(100) NOT NULL,
  `purchased_date` date NOT NULL,
  `price` double(12,2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `orders`
--

INSERT INTO `orders` (`id`, `customer_name`, `purchased_items`, `purchased_date`, `price`) VALUES
(1, 'Airi Satou', 'iPhone', '2020-05-07', 649.00),
(2, 'Angelica Ramos', 'Samsung Galaxy', '2020-11-10', 2500.00),
(3, 'Ashton Cox', 'Infinix Note 7', '2020-09-10', 299.09),
(4, 'Bradley Greer', 'Macbook Pro', '2020-11-26', 1799.50),
(5, 'Brenden Wagner', 'Samsung 50\" Smart 4K UHD TV ', '2020-11-27', 479.00),
(6, 'Brielle Williamson', '7 Series Curved LED 4K UHD', '2019-11-27', 269.00),
(7, 'Bruno Nash', 'iMac', '2019-11-28', 1999.05),
(8, 'Caesar Vance', 'Dell Inspiron 3573', '2019-11-30', 1999.05),
(9, 'Cara Stevens', 'Tlc 40inch tv Roku tv', '2019-12-07', 649.00),
(10, 'Cedric Kelly', 'Acer Aspire 3', '2021-01-13', 199.00);
//index.php
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>PHP MySQL Date Range Search with jQuery Ajax DatePicker</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css"/>
</head>
<body>
<br/>
<div class="container">
<h2 align="center">PHP MySQL Date Range Search with jQuery Ajax DatePicker</h2>
<br/>
<br/>
<div class="col-md-2">
    <input type="text" name="From" id="From" class="form-control" placeholder="From Date"/>
</div>
<div class="col-md-2">
    <input type="text" name="to" id="to" class="form-control" placeholder="To Date"/>
</div>
<div class="col-md-8">
    <input type="button" name="range" id="range" value="Range" class="btn btn-success"/>
</div>
<div class="clearfix"></div>
<br/>
<?php
include_once("dbcon.php");	
$query = "SELECT * FROM orders ORDER BY id desc";
$sql = mysqli_query($conn, $query);
?>
<div id="purchase_order">
    <table class="table table-bordered">
    <tr>
    <th width="100">ID</th>
    <th>Customer Name</th>
    <th>Purchased Item</th>
    <th>Purchased Date</th>
    <th width="100">Price</th>
    </tr>
<?php while($row= mysqli_fetch_array($sql)) { ?>
    <tr>
    <td><?php echo $row["id"]; ?></td>
    <td><?php echo $row["customer_name"]; ?></td>
    <td><?php echo $row["purchased_items"]; ?></td>
    <td><?php echo $row["purchased_date"]; ?></td>
    <td>$ <?php echo $row["price"]; ?></td>
    </tr>
<?php } ?>
    </table>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<script>
    $(document).ready(function(){
        $.datepicker.setDefaults({
            dateFormat: 'yy-mm-dd'
        });
        $(function(){
            $("#From").datepicker();
            $("#to").datepicker();
        });

        $('#range').click(function(){
            var From = $('#From').val();
            var to = $('#to').val();
            if(From != '' && to != '')
            {
                $.ajax({
                    url:"range.php",
                    method:"POST",
                    data:{From:From, to:to},
                    success:function(data)
                    {
                        $('#purchase_order').html(data);
                        $('#purchase_order').append(data.htmlresponse);
                    }
                });
            }
            else
            {
                alert("Please Select the Date");
            }
        });
    });
    </script>
</body>
</html>
range.php
//range.php
<?php
include_once("dbcon.php");
if(isset($_POST["From"], $_POST["to"]))
{
    $result = '';
    $query = "SELECT * FROM orders WHERE purchased_date BETWEEN '".$_POST["From"]."' AND '".$_POST["to"]."'";
    $sql = mysqli_query($conn, $query);
    $result .='
    <table class="table table-bordered">
    <tr>
    <th width="100">ID</th>
    <th>Customer Name</th>
    <th>Purchased Item</th>
    <th>Purchased Date</th>
    <th width="100">Price</th>
    </tr>';
    if(mysqli_num_rows($sql) > 0)
    {
        while($row = mysqli_fetch_array($sql))
        {
            $result .='
            <tr>
            <td>'.$row["id"].'</td>
            <td>'.$row["customer_name"].'</td>
            <td>'.$row["purchased_items"].'</td>
            <td>'.$row["purchased_date"].'</td>
            <td>'.$row["price"].'</td>
            </tr>';
        }
    }
    else
    {
        $result .='
        <tr>
        <td colspan="5">No Purchased Item Found</td>
        </tr>';
    }
    $result .='</table>';
    echo $result;
}
?>
dbcon.php
//dbcon.php
<?php
$conn = new mysqli('localhost','root','','testingdb');
if ($conn->connect_error) {
    die('Error : ('. $conn->connect_errno .') '. $conn->connect_error);
}
?>

Saturday, January 23, 2021

Python Flask Date Range Search with jQuery Ajax DatePicker MySQL Database

Python Flask Date Range Search with jQuery Ajax DatePicker MySQL Database

--
-- Table structure for table `orders`
--

CREATE TABLE `orders` (
  `id` int(11) NOT NULL,
  `customer_name` varchar(100) NOT NULL,
  `purchased_items` varchar(100) NOT NULL,
  `purchased_date` date NOT NULL,
  `price` double(12,2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `orders`
--

INSERT INTO `orders` (`id`, `customer_name`, `purchased_items`, `purchased_date`, `price`) VALUES
(1, 'Airi Satou', 'iPhone', '2020-05-07', 649.00),
(2, 'Angelica Ramos', 'Samsung Galaxy', '2020-11-10', 2500.00),
(3, 'Ashton Cox', 'Infinix Note 7', '2020-09-10', 299.09),
(4, 'Bradley Greer', 'Macbook Pro', '2020-11-26', 1799.50),
(5, 'Brenden Wagner', 'Samsung 50\" Smart 4K UHD TV ', '2020-11-27', 479.00),
(6, 'Brielle Williamson', '7 Series Curved LED 4K UHD', '2019-11-27', 269.00),
(7, 'Bruno Nash', 'iMac', '2019-11-28', 1999.05),
(8, 'Caesar Vance', 'Dell Inspiron 3573', '2019-11-30', 1999.05),
(9, 'Cara Stevens', 'Tlc 40inch tv Roku tv', '2019-12-07', 649.00),
(10, 'Cedric Kelly', 'Acer Aspire 3', '2021-01-13', 199.00);

app.py
 
#app.py
from flask import Flask, render_template, request, jsonify, flash, redirect
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():
    cursor = mysql.connection.cursor()
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    cur.execute("SELECT * FROM orders ORDER BY id desc")
    orders = cur.fetchall() 
    return render_template('index.html', orders=orders)
 
@app.route("/range",methods=["POST","GET"])
def range(): 
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor) 
    if request.method == 'POST':
        From = request.form['From']
        to = request.form['to']
        print(From)
        print(to)
        query = "SELECT * from orders WHERE purchased_date BETWEEN '{}' AND '{}'".format(From,to)
        cur.execute(query)
        ordersrange = cur.fetchall()
    return jsonify({'htmlresponse': render_template('response.html', ordersrange=ordersrange)})

if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Python Flask Date Range Search with jQuery Ajax DatePicker MySQL Database</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css"/>
</head>
<body>
<br/>
<div class="container">
<h2 align="center">Python Flask Date Range Search with jQuery Ajax DatePicker MySQL Database</h2>
<br/>
<br/>
<div class="col-md-2">
<input type="text" name="From" id="From" class="form-control" placeholder="From Date"/>
</div>
<div class="col-md-2">
<input type="text" name="to" id="to" class="form-control" placeholder="To Date"/>
</div>
<div class="col-md-8">
<input type="button" name="range" id="range" value="Range" class="btn btn-success"/>
</div>
<div class="clearfix"></div>
<br/>
<div id="purchase_order">
<table class="table table-bordered">
<tr>
<th width="5%">ID</th>
<th width="35%">Customer Name</th>
<th width="40%">Purchased Item</th>
<th width="10%">Purchased Date</th>
<th width="5%">Price</th>
</tr>
{% for row in orders %}
    <tr>
    <td>{{row.id}}</td>
    <td>{{row.customer_name}}</td>
    <td>{{row.purchased_items}}</td>
    <td>{{row.purchased_date}}</td>
    <td>{{row.price}}</td>
    </tr>
    {% endfor %}
</table>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<!-- Script -->
<script>
$(document).ready(function(){
    $.datepicker.setDefaults({
        dateFormat: 'yy-mm-dd'
    });
    $(function(){
        $("#From").datepicker();
        $("#to").datepicker();
    });
    $('#range').click(function(){
        var From = $('#From').val();
        var to = $('#to').val();
        if(From != '' && to != '')
        {
            $.ajax({
                url:"/range",
                method:"POST",
                data:{From:From, to:to},
                success:function(data)
                {
                    $('#purchase_order').html(data);
                    $('#purchase_order').append(data.htmlresponse);
                }
            });
        }
        else
        {
            alert("Please Select the Date");
        }
    });
});
</script>
</body>
</html>
templates/response.html
//templates/response.html
<table class="table table-bordered">
      <tr>
      <th width="5%">ID</th>
      <th width="35%">Customer Name</th>
      <th width="40%">Purchased Item</th>
      <th width="10%">Purchased Date</th>
      <th width="5%">Price</th>
      </tr>
      {% for row in ordersrange %}
          <tr>
          <td>{{row.id}}</td>
          <td>{{row.customer_name}}</td>
          <td>{{row.purchased_items}}</td>
          <td>{{row.purchased_date}}</td>
          <td>{{row.price}}</td>
          </tr>
      {% endfor %}
</table>

Python Flask Autosuggest using jQuery Ajax and Mysql database

Python Flask Autosuggest using jQuery Ajax and Mysql database

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

@app.route("/ajaxpost",methods=["POST","GET"])
def ajaxpost():
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)    
    if request.method == 'POST':
        queryString = request.form['queryString']
        print(queryString)
        query = "SELECT * from countries WHERE value LIKE '{}%' LIMIT 10".format(queryString)
        cur.execute(query)
        countries = cur.fetchall()
    return jsonify({'htmlresponse': render_template('response.html', countries=countries)})

if __name__ == "__main__":
    app.run(debug=True)
templates/index.html 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>Python Flask Autosuggest using jQuery Ajax and Mysql database</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script>
function suggest(inputString){
    if(inputString.length == 0) {
        $('#suggestions').fadeOut();
    } else {
        $('#country').addClass('load');
        $.post("/ajaxpost", {queryString: ""+inputString+""}, function(data){
                $('#suggestions').fadeIn();
                $('#suggestionsList').html(data); 
                $('#suggestionsList').append(data.htmlresponse);
                $('#country').removeClass('load');
        });
  }
}
function fill(thisValue) {
  $('#country').val(thisValue);
  setTimeout("$('#suggestions').fadeOut();", 600);
}
</script>
<style>
#country {
 width:200px;
 padding:3px;
 font-size:110%;
 vertical-align:middle;
}
.suggestionsBox {
 width: 200px;
 color: #fff;
 margin:0;
 padding:0;
 background:#86BAC7;
 top:0;
 left:0;
}
.suggestionList {
 margin: 0px;
 padding: 0px;
}
.suggestionList ul li {
 list-style:none;
 margin: 0px;
 padding: 6px;
 border-bottom:1px dotted #98BE56;
 cursor: pointer;
}
.suggestionList ul li:hover {
 background-color: #006E89;
 color:#000;text-align: left;
}
ul {
 font-family:Arial, Helvetica, sans-serif;
 font-size:11px;
 color:#FFF;
 padding:0;
 margin:0;
}
.load{
background-image:url(img/loader.gif);
background-position:right;
background-repeat:no-repeat;
}
#suggest {
 position:relative;
}
.sf_active{
 border:2px #8BB544 solid;
 background:#fff;
 color:#333;
}
</style>
</head>
<body> 
<div style="padding-left: 100px;">  
<p><h1>Python Flask Autosuggest using jQuery Ajax and Mysql database</h1></p>
<form id="form" action="#">
  <div id="suggest"><p><b>Start to type a country:</b></p>
   <input type="text" size="25" value="" id="country" onkeyup="suggest(this.value);" onblur="fill();" class="sf_active" />
   <div class="suggestionsBox" id="suggestions">
     <div class="suggestionList" id="suggestionsList">   </div>
  </div>
  </div>
</div>  
</form>
</body>
</html>
templates/response.html
//templates/response.html
<ul>
      {% for row in countries %} 
      <li onClick="fill('{{row.value}}')">{{row.value}}</li>
      {% endfor %}
</ul>

Friday, January 22, 2021

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

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

Create Database Table
--
-- Table structure for table `dragdrop`
--

CREATE TABLE `dragdrop` (
  `id` int(11) NOT NULL,
  `text` varchar(255) DEFAULT NULL,
  `listorder` int(11) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Dumping data for table `dragdrop`
--

INSERT INTO `dragdrop` (`id`, `text`, `listorder`) VALUES
(1, 'Ajax', 3),
(2, 'Jquery', 5),
(3, 'PHP', 6),
(4, 'Mysqli', 7),
(5, 'Javascript', 1),
(6, 'Java', 4),
(7, 'Python', 2);
app.py
 
#app.py
from flask import Flask, render_template, request, 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():
    cursor = mysql.connection.cursor()
    cur = mysql.connection.cursor(MySQLdb.cursors.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():
    cursor = mysql.connection.cursor()
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    if request.method == 'POST':
        number_of_rows= cur.execute("SELECT * FROM dragdrop")    
        #print(number_of_rows)       
        getorder = request.form['order']    
        print(getorder)
        order = getorder.split(",", number_of_rows)
        count=0    
        for value in order:
            count +=1
            print(count)                       
            cur.execute("UPDATE dragdrop SET listorder = %s WHERE id = %s ", [count, value])
            mysql.connection.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>Python Flask Dynamic Drag and Drop Order List With jQuery Ajax and Mysql 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>
<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>
<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>Python Flask Dynamic Drag and Drop Order List With jQuery Ajax and Mysql 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>
</body>
</html>

Python Flask Table Edit using jquery ajax and mysql Database

Python Flask Table Edit using jquery ajax and mysql Database

--
-- Table structure for table `topphpframework`
--

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

--
-- Dumping data for table `topphpframework`
--

INSERT INTO `topphpframework` (`id`, `name`) VALUES
(1, 'Laravel'),
(2, 'Codeigniter 2'),
(3, 'Symfony'),
(4, 'Yii framework '),
(5, 'Zend framework'),
(6, 'Cake php');
app.py
 
#app.py
from flask import Flask, render_template, request, 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():
    cursor = mysql.connection.cursor()
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    cur.execute("SELECT * FROM topphpframework ORDER BY id ASC")
    topphpframework = cur.fetchall() 
    return render_template('index.html', topphpframework=topphpframework)
    
@app.route("/ajax",methods=["POST","GET"])
def ajax():
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)    
    if request.method == 'POST':
        getid = request.form['id']
        getname = request.form['name']
        print(getid)
        cur.execute("UPDATE topphpframework SET name = %s WHERE id = %s ", [getname, getid])
        mysql.connection.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>Python Flask Table Edit using jquery ajax andd mysql Database</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<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>
<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>Python Flask Table Edit using jquery ajax and mysql 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>PHP 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.name}}</span>
    <input type="text" name="name" value="{{row.name}}" class="editbox" id="first_input_{{row.id}}" />
    </td>
  </tr>
  {% endfor %}
</table>
</div>
</body>
</html>

Thursday, January 21, 2021

Python Flask Read XML with jQuery Ajax

Python Flask Read XML with jQuery Ajax app.py
#app.py
from flask import Flask, render_template

app = Flask(__name__)
             
@app.route('/')
def index():
    return render_template('index.html')
    
if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Python Flask Read XML with jQuery Ajax</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  <script>
  $(document).ready(function () {
      $.ajax({
          type: "GET",
          url: "/static/music.xml",
          dataType: "xml",
          success: function_Parsxml
      });
  });
  function function_Parsxml(xml) {
      $('#load').fadeOut();
      $(xml).find("mostplayedsongs").each(function () {
          $(".main").append('<div class="song"><div class="title">' + $(this).find("Title").text() + '</div> <div class="Artist">' + $(this).find("Artist").text() + '</div></div>');
          $(".song").fadeIn(1000);
      });
  }
  </script>
  <style>
  .main{
  width:100%;
  margin:0 auto;
  }
  .song{
  width:208px;
  float:left;
  margin:10px;
  border:1px #dedede solid;
  padding:5px;
  display:none;
  }
  .title{
  margin-bottom:6px;}
  .Artist{font-size:12px; color:#999; margin-top:4px;}
  </style>
  </head>
  <body>
  <p><h2>Python Flask Read XML with jQuery Ajax</h2></p>
  <div class="main">
      <div align="center" class="loader"><img src="/static/img/loader.gif" id="load" align="absmiddle"/></div>
  </div>
  </body>
  </html>
 
static/music.xml
//static/music.xml
<?xml version="1.0" encoding="utf-8" ?>
<musictype>
<mostplayedsongs>
<Title>Sexyback</Title>
<Artist>Timberlake, Justin</Artist>
</mostplayedsongs>
 
<mostplayedsongs>
<Title>Wonderful Tonight</Title>
<Artist>Clapton, Eric</Artist>
</mostplayedsongs>
 
<mostplayedsongs>
<Title> Amazed</Title>
<Artist>Lonestar</Artist>
</mostplayedsongs>
 
</musictype>

Python Flask Dynamic Loading of ComboBox using jQuery Ajax and Mysql

Python Flask Dynamic Loading of ComboBox using jQuery Ajax and Mysql

Create Database table
--
-- 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, request, 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():
    cursor = mysql.connection.cursor()
    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("/get_child_categories",methods=["POST","GET"])
def get_child_categories():
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)    
    if request.method == 'POST':
        parent_id = request.form['parent_id']
        print(parent_id)
        cur.execute("SELECT * FROM carmodels WHERE brand_id = %s", [parent_id])
        carmodels = cur.fetchall()
    return jsonify({'htmlresponse': render_template('response.html', carmodels=carmodels)})
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>Python Flask Dynamic Loading of ComboBox using jQuery Ajax and Mysql</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.2.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
 $('#search_category_id').change(function(){
    $.post("/get_child_categories", {
     parent_id: $('#search_category_id').val(),
    }, function(response){ 
        $('#show_sub_categories').html(response);
        $('#show_sub_categories').append(response.htmlresponse);
    });
    return false;
  });
}); 
</script>
</head>
<body>
  <div class="container">
    <div class="row">
      <div class="col-lg-2"></div>
    <div class="col-lg-8">
    <h3 align="center">Python Flask Dynamic Loading of ComboBox using jQuery Ajax and Mysql</h3>
    <form action="#" name="form" id="form" method="post">
      <div class="form-group">
        <label>Select Category</label>
        <select name="search_category"  id="search_category_id" class="form-control">
          <option value="" selected="selected"></option>
          {% for row in carbrands %}
          <option value='{{row.brand_id}}'>{{row.brand_name}}</option>
          {% endfor %}
          </select> 
      </div>
      <div id="show_sub_categories"></div>
      <button type="submit" class="btn btn-primary">Submit</button>
    </form>
    </div>
    <div class="col-lg-2"></div>
  </div>
</div>
</body>
</html>
templates/response.html
//templates/response.html
<div class="form-group">
      <label>Select Sub Category</label>
      <select name="sub_category"  id="sub_category_id" class="form-control">
         <option value="" selected="selected"></option>
          {% for row in carmodels %} 
          <option value="{{row.model_id}}">{{row.car_models}}</option>
          {% endfor %}
      </select> 
</div>

Sunday, January 17, 2021

Python Flask Live Data Search using Jquery Ajax and MySql Database


Python Flask Live Data Search using Jquery Ajax and MySql Database

Database table
CREATE TABLE `employee` (
  `id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `email` varchar(100) NOT NULL,
  `phone` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
app.py
#app.py
from flask import Flask, render_template, request, 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():
    return render_template('index.html')

@app.route("/ajaxlivesearch",methods=["POST","GET"])
def ajaxlivesearch():
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    if request.method == 'POST':
        search_word = request.form['query']
        print(search_word)
        if search_word == '':
            query = "SELECT * from employee ORDER BY id"
            cur.execute(query)
            employee = cur.fetchall()
        else:    
            query = "SELECT * from employee WHERE name LIKE '%{}%' OR email LIKE '%{}%' OR phone LIKE '%{}%' ORDER BY id DESC LIMIT 20".format(search_word,search_word,search_word)
            cur.execute(query)
            numrows = int(cur.rowcount)
            employee = cur.fetchall()
            print(numrows)
    return jsonify({'htmlresponse': render_template('response.html', employee=employee, numrows=numrows)})
    
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>Python Flask Live Data Search using Jquery Ajax and MySql Database</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  load_data();
  function load_data(query)
  {
   $.ajax({
    url:"/ajaxlivesearch",
    method:"POST",
    data:{query:query},
    success:function(data)
    {
      $('#result').html(data);
      $("#result").append(data.htmlresponse);
    }
   });
  }
  $('#search_text').keyup(function(){
    var search = $(this).val();
    if(search != ''){
    load_data(search);
   }else{
    load_data();
   }
  });
});
</script>
</head>
<body>
<div class="container search-table">
<p><h2 align="center">Python Flask Live Data Search using Jquery Ajax and MySql Database</h2></p>
            <div class="search-box">
                <div class="row">
                    <div class="col-md-3">
                        <h5>Search All Fields</h5>
                    </div>
                    <div class="col-md-9">
                        <input type="text" name="search_text" id="search_text" class="form-control" placeholder="Search all fields e.g. HTML">
                    </div> 
                </div>
            </div>
   <div id="result"></div>
</div>
<style>
.search-table{
    padding: 10%;
    margin-top: -6%;
}
.search-box{
    background: #c1c1c1;
    border: 1px solid #ababab;
    padding: 3%;
}
.search-box input:focus{
    box-shadow:none;
    border:2px solid #eeeeee;
}
.search-list{
    background: #fff;
    border: 1px solid #ababab;
    border-top: none;
}
.search-list h3{
    background: #eee;
    padding: 3%;color:#fe6f41;
    margin-bottom: 0%;
}
</style>
</body>
</html>
templates/response.html
//templates/response.html
<h3>{{numrows}} Records Found</h3>
<table class="table table-striped custab">
  <thead>
      <tr>
         <th>Name</th>
         <th>Email</th>
         <th>Phone</th>
      </tr>
  </thead>
  <tbody>
{% for row in employee %}  
   <tr>
    <td>{{row.name}}</td>
    <td>{{row.email}}</td>
    <td>{{row.phone}}</td>
   </tr>
{% endfor %} 

Saturday, January 16, 2021

Jquery Ajax Python Flask and Mysql database Search Box SQL LIKE operator


Jquery Ajax Python Flask and Mysql database Search Box SQL LIKE operator

Create Database Table
CREATE TABLE `tblprogramming` (
  `id` int(11) NOT NULL,
  `title` varchar(250) NOT NULL,
  `category` varchar(255) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

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

@app.route("/searchdata",methods=["POST","GET"])
def searchdata():
    if request.method == 'POST':
        search_word = request.form['search_word']
        print(search_word)
        cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        query = "SELECT * from tblprogramming WHERE title LIKE '%{}%' ORDER BY id DESC LIMIT 20".format(search_word)
        cur.execute(query)
        programming = cur.fetchall()
    return jsonify({'data': render_template('response.html', programming=programming)})

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>Jquery Ajax Python Flask and Mysql database Search Box SQL LIKE operator</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
  $(".search_button").click(function() {
      var search_word = $("#search_box").val();
      var dataString = 'search_word='+ search_word;
      if(search_word==''){
      }else{
        $.ajax({
          type: "POST",
          url: "/searchdata",
          data: dataString,
          cache: false,
          beforeSend: function(html) {
              document.getElementById("insert_search").innerHTML = ''; 
              $("#flash").show();
              $("#searchword").show();
              $(".searchword").html(search_word);
              $("#flash").html('<img src="/static/img/loader.gif" align="absmiddle"> Loading Results...');
            },
          success: function(html){
              $("#insert_search").show();
              $("#insert_search").append(html.data);
              $("#flash").hide();
          }
        });
      }
    return false;
  });
});
</script>
</head>
<body>
<div align="center">
  <div style="width:700px">
  <div style="margin-top:20px; text-align:left">
    <p align="center"><h1>Jquery Ajax Python Flask and Mysql database Search Box SQL LIKE operator</h1></p>
    <form method="get" action="">
    <input type="text" name="search" id="search_box" class='search_box'/>
    <input type="submit" value="Search" class="search_button" /><br />
    <span style="color:#666666; font-size:14px; font-family:Arial, Helvetica, sans-serif;"><b>Ex :</b> Javascript</span>
    </form>
  </div>   
  <div>
    <div id="searchword">Search results for <span class="searchword"></span></div>
    <div id="flash"></div>
    <ol id="insert_search" class="update"></ol>
  </div>
  </div>
</div>
<style>
body{
font-family:Arial, Helvetica, sans-serif;
}
a
{
color:#DF3D82;
text-decoration:none
}
a:hover
{
color:#DF3D82;
text-decoration:underline;
}
#search_box{
 padding:3px; border:solid 1px #666666; width:400px; height:45px; font-size:18px;-moz-border-radius: 6px;-webkit-border-radius: 6px;
}
.search_button{
 height:50px;border:#fe6f41 solid 1px; padding-left:9px;padding-right:9px;padding-top:9px;padding-bottom:9px; color:#000; font-weight:bold; font-size:16px;-moz-border-radius: 6px;-webkit-border-radius: 6px;
}
ol.update{
 list-style:none;font-size:1.1em; margin-top:20px;padding-left:0; 
}
#flash{
 margin-top:20px;
 text-align:left;
}
#searchword{
 text-align:left; margin-top:20px; display:none;
 font-family:Arial, Helvetica, sans-serif;
 font-size:16px;
 color:#000;
}
.searchword{
 font-weight:bold;
 color:#fe6f41;
}
ol.update li{ border-bottom:#dedede dashed 1px; text-align:left;padding-top:10px;padding-bottom:10px;}
ol.update li:first-child{ border-top:#dedede dashed 1px; text-align:left}
</style>
</body>
</html>
templates/response.html
//templates/response.html
{% for row in programming %}  
  <li>{{row.title}} <br/><span style='font-size:12px;'>{{row.category}}</span></li>
  {% endfor %} 

Related Post