article

Saturday, February 20, 2021

Python Flask Editable Select Box using jQuery Ajax and Mysql Database



Python Flask Editable Select Box using jQuery Ajax and Mysql Database

--
-- Table structure for table `country`
--

CREATE TABLE `country` (
  `id` int(6) NOT NULL,
  `country` varchar(250) NOT NULL DEFAULT ''
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Dumping data for table `country`
--

INSERT INTO `country` (`id`, `country`) VALUES
(1, 'Afghanistan'),
(2, 'Aringland Islands'),
(3, 'Albania'),
(4, 'Algeria'),
(5, 'American Samoa'),
(6, 'Andorra'),
(7, 'Angola'),
(8, 'Anguilla'),
(9, 'Antarctica'),
(10, 'Antigua and Barbuda'),
(11, 'Argentina'),
(12, 'Armenia'),
(13, 'Aruba'),
(14, 'Australia'),
(15, 'Austria'),
(16, 'Azerbaijan'),
(17, 'Bahamas'),
(18, 'Bahrain'),
(19, 'Bangladesh'),
(20, 'Barbados'),
(21, 'Belarus'),
(22, 'Belgium'),
(23, 'Belize'),
(24, 'Benin'),
(25, 'Bermuda'),
(26, 'Bhutan'),
(27, 'Bolivia'),
(28, 'Bosnia and Herzegovina'),
(29, 'Botswana'),
(30, 'Bouvet Island'),
(31, 'Brazil'),
(32, 'British Indian Ocean territory'),
(33, 'Brunei Darussalam'),
(34, 'Bulgaria'),
(35, 'Burkina Faso'),
(36, 'Burundi'),
(37, 'Cambodia'),
(38, 'Cameroon'),
(39, 'Canada'),
(40, 'Cape Verde'),
(41, 'Cayman Islands'),
(42, 'Central African Republic'),
(43, 'Chad'),
(44, 'Chile'),
(45, 'China'),
(46, 'Christmas Island'),
(47, 'Cocos (Keeling) Islands'),
(48, 'Colombia'),
(49, 'Comoros'),
(50, 'Congo'),
(51, 'Congo'),
(52, ' Democratic Republic'),
(53, 'Cook Islands'),
(54, 'Costa Rica'),
(55, 'Ivory Coast (Ivory Coast)'),
(56, 'Croatia (Hrvatska)'),
(57, 'Cuba'),
(58, 'Cyprus'),
(59, 'Czech Republic'),
(60, 'Denmark'),
(61, 'Djibouti'),
(62, 'Dominica'),
(63, 'Dominican Republic'),
(64, 'East Timor'),
(65, 'Ecuador'),
(66, 'Egypt'),
(67, 'El Salvador'),
(68, 'Equatorial Guinea'),
(69, 'Eritrea'),
(70, 'Estonia'),
(71, 'Ethiopia'),
(72, 'Falkland Islands'),
(73, 'Faroe Islands'),
(74, 'Fiji'),
(75, 'Finland'),
(76, 'France'),
(77, 'French Guiana'),
(78, 'French Polynesia'),
(79, 'French Southern Territories'),
(80, 'Gabon'),
(81, 'Gambia'),
(82, 'Georgia'),
(83, 'Germany'),
(84, 'Ghana'),
(85, 'Gibraltar'),
(86, 'Greece'),
(87, 'Greenland'),
(88, 'Grenada'),
(89, 'Guadeloupe'),
(90, 'Guam'),
(91, 'Guatemala'),
(92, 'Guinea'),
(93, 'Guinea-Bissau'),
(94, 'Guyana'),
(95, 'Haiti'),
(96, 'Heard and McDonald Islands'),
(97, 'Honduras'),
(98, 'Hong Kong'),
(99, 'Hungary'),
(100, 'Iceland'),
(101, 'India'),
(102, 'Indonesia'),
(103, 'Iran'),
(104, 'Iraq'),
(105, 'Ireland'),
(106, 'Israel'),
(107, 'Italy'),
(108, 'Jamaica'),
(109, 'Japan'),
(110, 'Jordan'),
(111, 'Kazakhstan'),
(112, 'Kenya'),
(113, 'Kiribati'),
(114, 'Korea (north)'),
(115, 'Korea (south)'),
(116, 'Kuwait'),
(117, 'Kyrgyzstan'),
(118, 'Lao People\'s Democratic Republic'),
(119, 'Latvia'),
(120, 'Lebanon'),
(121, 'Lesotho'),
(122, 'Liberia'),
(123, 'Libyan Arab Jamahiriya'),
(124, 'Liechtenstein'),
(125, 'Lithuania'),
(126, 'Luxembourg'),
(127, 'Macao'),
(128, 'Macedonia'),
(129, 'Madagascar'),
(130, 'Malawi'),
(131, 'Malaysia'),
(132, 'Maldives'),
(133, 'Mali'),
(134, 'Malta'),
(135, 'Marshall Islands'),
(136, 'Martinique'),
(137, 'Mauritania'),
(138, 'Mauritius'),
(139, 'Mayotte'),
(140, 'Mexico'),
(141, 'Micronesia'),
(142, 'Moldova'),
(143, 'Monaco'),
(144, 'Mongolia'),
(145, 'Montserrat'),
(146, 'Morocco'),
(147, 'Mozambique'),
(148, 'Myanmar'),
(149, 'Namibia'),
(150, 'Nauru'),
(151, 'Nepal'),
(152, 'Netherlands'),
(153, 'Netherlands Antilles'),
(154, 'New Caledonia'),
(155, 'New Zealand'),
(156, 'Nicaragua'),
(157, 'Niger'),
(158, 'Nigeria'),
(159, 'Niue'),
(160, 'Norfolk Island'),
(161, 'Northern Mariana Islands'),
(162, 'Norway'),
(163, 'Oman'),
(164, 'Pakistan'),
(165, 'Palau'),
(166, 'Palestinian Territories'),
(167, 'Panama'),
(168, 'Papua New Guinea'),
(169, 'Paraguay'),
(170, 'Peru'),
(171, 'Philippines'),
(172, 'Pitcairn'),
(173, 'Poland'),
(174, 'Portugal'),
(175, 'Puerto Rico'),
(176, 'Qatar'),
(177, 'Runion'),
(178, 'Romania'),
(179, 'Russian Federation'),
(180, 'Rwanda'),
(181, 'Saint Helena'),
(182, 'Saint Kitts and Nevis'),
(183, 'Saint Lucia'),
(184, 'Saint Pierre and Miquelon'),
(185, 'Saint Vincent and the Grenadines'),
(186, 'Samoa'),
(187, 'San Marino'),
(188, 'Sao Tome and Principe'),
(189, 'Saudi Arabia'),
(190, 'Senegal'),
(191, 'Serbia and Montenegro'),
(192, 'Seychelles'),
(193, 'Sierra Leone'),
(194, 'Singapore'),
(195, 'Slovakia'),
(196, 'Slovenia'),
(197, 'Solomon Islands'),
(198, 'Somalia'),
(199, 'South Africa'),
(200, 'South Georgia and the South Sandwich Islands'),
(201, 'Spain'),
(202, 'Sri Lanka'),
(203, 'Sudan'),
(204, 'Suriname'),
(205, 'Svalbard and Jan Mayen Islands'),
(206, 'Swaziland'),
(207, 'Sweden'),
(208, 'Switzerland'),
(209, 'Syria'),
(210, 'Taiwan'),
(211, 'Tajikistan'),
(212, 'Tanzania'),
(213, 'Thailand'),
(214, 'Togo'),
(215, 'Tokelau'),
(216, 'Tonga'),
(217, 'Trinidad and Tobago'),
(218, 'Tunisia'),
(219, 'Turkey'),
(220, 'Turkmenistan'),
(221, 'Turks and Caicos Islands'),
(222, 'Tuvalu'),
(223, 'Uganda'),
(224, 'Ukraine'),
(225, 'United Arab Emirates'),
(226, 'United Kingdom'),
(227, 'United States of America'),
(228, 'Uruguay'),
(229, 'Uzbekistan'),
(230, 'Vanuatu'),
(231, 'Vatican City'),
(232, 'Venezuela'),
(233, 'Vietnam'),
(234, 'Virgin Islands (British)'),
(235, 'Virgin Islands (US)'),
(236, 'Wallis and Futuna Islands'),
(237, 'Western Sahara'),
(238, 'Yemen'),
(239, 'Zaire'),
(240, 'Zambia'),
(241, 'Zimbabwe');

--
-- Indexes for dumped tables
--

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

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `country`
--
ALTER TABLE `country`
  MODIFY `id` int(6) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=243;

--
-- Table structure for table `tbl_user`
--

CREATE TABLE `tbl_user` (
  `userid` int(11) NOT NULL,
  `fullname` varchar(50) NOT NULL,
  `country` varchar(100) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

--
-- Indexes for table `tbl_user`
--
ALTER TABLE `tbl_user`
  ADD PRIMARY KEY (`userid`);

--
-- AUTO_INCREMENT for dumped tables
--

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

jQuery Editable Select is a jQuery plugin that transforms a select into an input field where single elements are shown in real-time according to the entered characters. It scales down to a real select list when javascript is not available.

https://github.com/indrimuska/jquery-editable-select

See demos here: http://indrimuska.github.io/jquery-editable-select/
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(): 
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    cur.execute("SELECT * FROM country ORDER BY country ASC")
    countrylist = cur.fetchall()
    return render_template('index.html', countrylist=countrylist)

@app.route("/insert",methods=["POST","GET"])
def insert():
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    if request.method == 'POST':
        fullname = request.form['name']
        country = request.form['country']
        cur.execute("INSERT INTO tbl_user (fullname, country) VALUES (%s,%s)",[fullname,country])
        mysql.connection.commit()       
        cur.close()
    return jsonify('New Records added successfully')


if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html>
<head>
<title>Python Flask Editable Select Box 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>

<script src="http://rawgithub.com/indrimuska/jquery-editable-select/master/dist/jquery-editable-select.min.js"></script>
<link href="http://rawgithub.com/indrimuska/jquery-editable-select/master/dist/jquery-editable-select.min.css" rel="stylesheet">
</head>  
<body>  
<div class="container">  
   <br />
   <h2 align="center">Python Flask Editable Select Box using jQuery Ajax and Mysql Database</h2><br />
   <div class="row">
    <div class="col-md-3"></div>
    <div class="col-md-6">
     <form method="post" id="sample_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>Select Country</label>
       <select name="country" id="country" class="form-control">
        {% for row in countrylist %}
            <option value="{{row.country}}">{{row.country}}</option>
        {% endfor %} 
       </select>
      </div>
      <div class="form-group">
       <input type="submit" name="Save" id="save" class="btn btn-success" value="Save" />
      </div>
     </form>
    </div>
   </div>
  </div>
  <script>  
$(document).ready(function(){
	$('#country').editableSelect();
 
	$('#sample_form').on('submit', function(event){
		event.preventDefault();
		if($('#name').val() == '') {
		   alert("Enter Name");
		   return false;
		}else if($('#country').val() == ''){
		   alert("Select Country");
		   return false;
		}else{
		   $.ajax({
				url:"/insert",
				method:"POST",
				data:$(this).serialize(),
				success:function(data)
				{
				 alert(data);
				 $('#sample_form')[0].reset();
				}
		   });
		}
	});
});  
</script>
</body>  
</html> 

Friday, February 19, 2021

Delete Multiple Records using PHP Mysql and Jquey Ajax with Animated Effect

Delete Multiple Records using PHP Mysql and Jquey Ajax with Animated Effect

this post a user select multiple records using checkbox fields and click the delete button a loading image gif show and a successfully message display and animate effect every row selected without refresh the page

--
-- Table structure for table `employee`
--

CREATE TABLE `employee` (
  `id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `position` varchar(100) NOT NULL,
  `office` varchar(100) NOT NULL,
  `age` int(11) NOT NULL,
  `salary` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `employee`
--

INSERT INTO `employee` (`id`, `name`, `position`, `office`, `age`, `salary`) VALUES
(1, 'Caite Ednalan', 'Accountant', 'Tokyo', 36, 5689),
(2, 'Mark Oto Ednalan', 'Chief Executive Officer (CEO)', 'London', 56, 5648),
(3, 'Jacob thompson', 'Junior Technical Author', 'San Francisco', 23, 5689),
(4, 'cylde Ednalan', 'Software Engineer', 'Olongapo', 23, 54654),
(5, 'Angelica Ramos', 'Software Engineer', 'San Francisco', 26, 5465),
(6, 'Airi Satou', 'Integration Specialist', 'New York', 53, 56465),
(8, 'Tiger Nixon', 'Software Engineer', 'London', 45, 456),
(9, 'Airi Satou', 'Pre-Sales Support', 'New York', 25, 4568),
(10, 'Angelica Ramos', 'Sales Assistant', 'New York', 45, 456),
(11, 'Ashton updated', 'Senior Javascript Developer', 'Olongapo', 45, 54565),
(12, 'Bradley Greer', 'Regional Director', 'San Francisco', 27, 5485),
(13, 'Brenden Wagner', 'Javascript Developer', 'San Francisco', 38, 65468),
(14, 'Brielle Williamson', 'Personnel Lead', 'Olongapo', 56, 354685),
(15, 'Bruno Nash', 'Customer Support', 'New York', 36, 65465),
(16, 'cairocoders', 'Sales Assistant', 'Sydney', 45, 56465),
(17, 'Zorita Serrano', 'Support Engineer', 'San Francisco', 38, 6548),
(18, 'Zenaida Frank', 'Chief Operating Officer (COO)', 'San Francisco', 39, 545),
(19, 'Yuri Berry', 'Accountant', 'Tokyo', 38, 5468);

--
-- Indexes for dumped tables
--

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

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `employee`
--
ALTER TABLE `employee`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=20;
index.php
//index.php
<!DOCTYPE html>
<html>
<head>
<title>Delete Multiple Records using PHP Mysql and Jquey Ajax with Animated Effect</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">  
            <br />
   <div class="table-responsive">  
    <h3 align="center">Delete Multiple Records using PHP Mysql and Jquey Ajax with Animated Effect</h3><br />
	<div id="targetLayer" class="btn btn-success" style="display:none;width:100%;margin-bottom: 10px;"></div>
    <div id="loader-icon" style="display:none;"><img src="img/loader.gif" /></div>
    <div class="table-responsive">
                    <table class="table table-bordered">
                        <thead>
                        <tr>
                            <th width="5%"><button type="button" name="delete_all" id="delete_all" class="btn btn-danger btn-xs">Delete</button></th>
                            <th>Name</th>
                            <th>Position</th>
                            <th>Office</th>
                            <th>Age</th>
                            <th>Salary</th>
                        </tr>
                        </thead>
                        <?php
						include('dbcon.php');
						$result = $conn->query("SELECT * FROM employee ORDER BY id DESC");
                        foreach($result as $row)
                        {
                            echo '
                            <tr>
                                <td>
                                    <input type="checkbox" class="delete_checkbox" value="'.$row["id"].'" />
                                </td>
                                <td>'.$row["name"].'</td>
                                <td>'.$row["position"].'</td>
                                <td>'.$row["office"].'</td>
                                <td>'.$row["age"].'</td>
                                <td>'.$row["salary"].'</td>
                            </tr>
                            ';
                        }
                        ?>
                    </table>
                </div>
   </div>  
  </div>
<style>
.removeRow {background-color: #ff7373;color:#FFFFFF;}
</style>
<script>  
$(document).ready(function(){ 
    $('.delete_checkbox').click(function(){
        if($(this).is(':checked')) {
            $(this).closest('tr').addClass('removeRow');
        }else{
            $(this).closest('tr').removeClass('removeRow');
        }
    });
    $('#delete_all').click(function(){
        var checkbox = $('.delete_checkbox:checked');
        if(checkbox.length > 0){
            var checkbox_value = [];
            $(checkbox).each(function(){
                checkbox_value.push($(this).val());
            });
            $('#loader-icon').show();
            $('#targetLayer').hide();
            $.ajax({
                url:"delete.php",
                method:"POST",
                data:{checkbox_value:checkbox_value},
                success:function(data)
                {
                    $('.removeRow').fadeOut(1500);
					$('#loader-icon').hide();
                    $('#targetLayer').show();
                    $('#targetLayer').html(data);
                }
            });
        }else {
            alert("Select atleast one records");
        }
    });
});  
</script>
</body>  
</html> 
delete.php
//delete.php
<?php
include('dbcon.php');
if(isset($_POST["checkbox_value"]))
{
	for($count = 0; $count < count($_POST["checkbox_value"]); $count++)
	{
	  $sql = "DELETE FROM employee WHERE id = '".$_POST['checkbox_value'][$count]."'";
	  $conn->query($sql);
	}
	echo "Records Succefully Deleted";
}	
?>
dbcon.php
//dbcon.php
<?php
$conn = new mysqli('localhost','root','','testingdb');
if ($conn->connect_error) {
    die('Error : ('. $conn->connect_errno .') '. $conn->connect_error);
}
?>

Delete Multiple Records using Python Flask Mysql and Jquey Ajax with Animated Effect

Delete Multiple Records using Python Flask Mysql and Jquey Ajax with Animated Effect

this post a user select multiple records using checkbox fields and click the delete button a loading image gif show and a successfully message display and animate effect every row selected without refresh the page


The jQuery Form Plugin allows you to easily and unobtrusively upgrade HTML forms to use AJAX. The main methods, ajaxForm and ajaxSubmit, gather information from the form element to determine how to manage the submit process. Both of these methods support numerous options which allow you to have full control over how the data is submitted.


--
-- Table structure for table `employee`
--

CREATE TABLE `employee` (
  `id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `position` varchar(100) NOT NULL,
  `office` varchar(100) NOT NULL,
  `age` int(11) NOT NULL,
  `salary` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `employee`
--

INSERT INTO `employee` (`id`, `name`, `position`, `office`, `age`, `salary`) VALUES
(1, 'Caite Ednalan', 'Accountant', 'Tokyo', 36, 5689),
(2, 'Mark Oto Ednalan', 'Chief Executive Officer (CEO)', 'London', 56, 5648),
(3, 'Jacob thompson', 'Junior Technical Author', 'San Francisco', 23, 5689),
(4, 'cylde Ednalan', 'Software Engineer', 'Olongapo', 23, 54654),
(5, 'Angelica Ramos', 'Software Engineer', 'San Francisco', 26, 5465),
(6, 'Airi Satou', 'Integration Specialist', 'New York', 53, 56465),
(8, 'Tiger Nixon', 'Software Engineer', 'London', 45, 456),
(9, 'Airi Satou', 'Pre-Sales Support', 'New York', 25, 4568),
(10, 'Angelica Ramos', 'Sales Assistant', 'New York', 45, 456),
(11, 'Ashton updated', 'Senior Javascript Developer', 'Olongapo', 45, 54565),
(12, 'Bradley Greer', 'Regional Director', 'San Francisco', 27, 5485),
(13, 'Brenden Wagner', 'Javascript Developer', 'San Francisco', 38, 65468),
(14, 'Brielle Williamson', 'Personnel Lead', 'Olongapo', 56, 354685),
(15, 'Bruno Nash', 'Customer Support', 'New York', 36, 65465),
(16, 'cairocoders', 'Sales Assistant', 'Sydney', 45, 56465),
(17, 'Zorita Serrano', 'Support Engineer', 'San Francisco', 38, 6548),
(18, 'Zenaida Frank', 'Chief Operating Officer (COO)', 'San Francisco', 39, 545),
(19, 'Yuri Berry', 'Accountant', 'Tokyo', 38, 5468);

--
-- Indexes for dumped tables
--

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

--
-- AUTO_INCREMENT for dumped tables
--

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



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(): 
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    cur.execute("SELECT * FROM employee ORDER BY id DESC")
    employeelist = cur.fetchall()
    return render_template('index.html', employeelist=employeelist)

@app.route("/delete",methods=["POST","GET"])
def delete():
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    for getid in request.form.getlist('checkdelete'):
        print(getid)
        cur.execute('DELETE FROM employee WHERE id = {0}'.format(getid))
        mysql.connection.commit()       
    cur.close()
    return jsonify('Records deleted successfully')
    
if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html>
<head>
<title>Delete Multiple Records using Python Flask Mysql and Jquey Ajax with Animated Effect</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>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.3.0/jquery.form.min.js" integrity="sha384-qlmct0AOBiA2VPZkMY3+2WqkHtIQ9lSdAsAn5RUJD/3vA5MKDgSGcdmIv4ycVxyn" crossorigin="anonymous"></script>
</head>  
    <body>  
        <div class="container">  
            <br />
   <div class="table-responsive">  
    <h3 align="center">Delete Multiple Records using Python Flask Mysql and Jquey Ajax with Animated Effect</h3><br />
    <div class="table-responsive">
        <div id="targetLayer" class="btn btn-success" style="display:none;width:100%;margin-bottom: 10px;"></div>
        <div id="loader-icon" style="display:none;"><img src="/static/img/loader.gif" /></div>
        <form id="deleteall" action="/delete" method="post">
                    <table class="table table-bordered">
                        <thead>
                        <tr>
                            <th width="5%">
                                <input type="submit" value="Delete" name="delete_all" id="delete_all" class="btn btn-danger btn-xs" />
                            <th>Name</th>
                            <th>Position</th>
                            <th>Office</th>
                            <th>Age</th>
                            <th>Salary</th>
                        </tr>
                        </thead>
                        {% for row in employeelist %}
                            <tr>
                                <td>
                                    <input type="checkbox" name="checkdelete" id="checkdelete" class="delete_checkbox" value="{{row.id}}" />
                                </td>
                                <td>{{row.name}}</td>
                                <td>{{row.position}}</td>
                                <td>{{row.office}}</td>
                                <td>{{row.age}}</td>
                                <td>$ {{ "%.2f"|format(row.salary) }}</td>
                            </tr>
                        {% endfor %}    
                    </table>
        </form>        
                </div>
   </div>  
  </div>
<style>
.removeRow {background-color: #ff7373;color:#FFFFFF;}
</style>
<script>  
$(document).ready(function(){ 
    $('.delete_checkbox').click(function(){
        if($(this).is(':checked')) {
            $(this).closest('tr').addClass('removeRow');
        }else{
            $(this).closest('tr').removeClass('removeRow');
        }
    });
    $('#deleteall').submit(function(event){
        if($('#checkdelete').val()){
            event.preventDefault();
            $('#loader-icon').show();
            $('#targetLayer').hide();
            $(this).ajaxSubmit({
                target: '#targetLayer',
                success:function(data){
                    $('.removeRow').fadeOut(1500);
                    $('#loader-icon').hide();
                    $('#targetLayer').show();
                    $('#targetLayer').html(data);
                },
                resetForm: true
            });
        }
        return false;
    });
});  
</script>
</body>  
</html> 

Product Filters Price Range Using PHP Mysql and Jquery Ajax

Product Filters Price Range Using PHP Mysql and Jquery Ajax

--
-- Table structure for table `product`
--

CREATE TABLE `product` (
  `pid` int(11) NOT NULL,
  `name` varchar(70) DEFAULT NULL,
  `image` varchar(255) NOT NULL,
  `category` varchar(70) DEFAULT NULL,
  `price` int(11) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Dumping data for table `product`
--

INSERT INTO `product` (`pid`, `name`, `image`, `category`, `price`) VALUES
(1, 'Samsung Galaxy A10S', '1.jpg', 'Mobile', 520),
(2, 'HP Laptop - 17z-ca100 ', '2.jpg', 'Laptop', 1600),
(3, '3 IN 1 CAR VOLTMETER', '3.jpg', 'Car', 2020),
(4, 'Gucci G-Timeless', '4.jpg', 'Watch', 320),
(5, 'Infinix Hot S3', '5.jpg', 'Mobile', 150),
(6, 'VIVO V9 Youth', '6.jpeg', 'Laptop', 3500),
(7, 'Moto E4 Plus', '7.jpeg', 'Car', 250),
(8, 'Lenovo K8 Plus', '8.jpeg', 'Watch', 4500);

--
-- Indexes for dumped tables
--

--
-- Indexes for table `product`
--
ALTER TABLE `product`
  ADD PRIMARY KEY (`pid`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `product`
--
ALTER TABLE `product`
  MODIFY `pid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9;

Jqueryui Slider https://jqueryui.com/slider/
index.php
//index.php
<!DOCTYPE html>
<html>
<head>
<title>Product Filters Price Range 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" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<div class="container">
    <div class="row">
    <br />
    <h2 align="center">Product Filters Price Range Using PHP Mysql and Jquery Ajax</h2>
    <br />
		<div class="col-md-3">                				
			<div class="list-group">
				<h3>Price</h3>
				<input type="hidden" id="hidden_minimum_price" value="0" />
                <input type="hidden" id="hidden_maximum_price" value="65000" />
                <p id="price_show">10 - 5000</p>
                <div id="price_range"></div>
            </div>				
        </div>
		<div class="col-md-9">
            <br />
           <div class="row filter_data">
        </div>
    </div>
    </div>
</div>
<style>
#loading{text-align:center; background: url('images/loading.gif') no-repeat center; height: 150px;}
</style>
<script>
$(document).ready(function(){
    filter_data();
    function filter_data()
    {
        $('.filter_data').html('<div id="loading" style="" ></div>');
        var action = 'fetch_data';
        var minimum_price = $('#hidden_minimum_price').val();
        var maximum_price = $('#hidden_maximum_price').val();
        $.ajax({
            url:"fetch_data.php",
            method:"POST",
            data:{action:action, minimum_price:minimum_price, maximum_price:maximum_price},
            success:function(data){
                $('.filter_data').html(data);
            }
        });
    }
    $('#price_range').slider({
        range:true,
        min:50,
        max:5000,
        values:[50, 5000],
        step:50,
        stop:function(event, ui)
        {
            $('#price_show').html(ui.values[0] + ' - ' + ui.values[1]);
            $('#hidden_minimum_price').val(ui.values[0]);
            $('#hidden_maximum_price').val(ui.values[1]);
            filter_data();
        }
    });
});
</script>
</body>
</html>
fetch_data.php
//fetch_data.php
<?php
include('dbcon.php');
if(isset($_POST["action"]))
{
	$query = $conn->query("SELECT * FROM product");
	if(isset($_POST["minimum_price"], $_POST["maximum_price"]) && !empty($_POST["minimum_price"]) && !empty($_POST["maximum_price"]))
	{
		$query = $conn->query("SELECT * FROM product WHERE price BETWEEN '".$_POST["minimum_price"]."' AND '".$_POST["maximum_price"]."'");
	}
	$total_row = mysqli_num_rows($query);
	$output = '';
	if($total_row > 0){
		while ($row = $query ->fetch_object()) {
			$output .= '
			<div class="col-sm-4 col-lg-3 col-md-3">
				<div style="border:1px solid #ccc; border-radius:5px; padding:16px; margin-bottom:16px; height:320px;">
					<img src="images/'. $row->image .'" alt="" class="img-responsive" >
					<p align="center"><strong><a href="#">'. $row->name .'</a></strong></p>
					<h4 style="text-align:center;" class="text-danger" >'. $row->price .'</h4>
				</div>
			</div>';
		}
	}else{
		$output = '<h3>No Data Found</h3>';
	}
	echo $output;
}
?>
dbcon.php
//dbcon.php
<?php
$conn = new mysqli('localhost','root','','testingdb');
if ($conn->connect_error) {
    die('Error : ('. $conn->connect_errno .') '. $conn->connect_error);
}
?>

Product Filters Price Range Using Python Flask Mysql and Jquery Ajax

Product Filters Price Range Using Python Flask Mysql and Jquery Ajax

--
-- Table structure for table `product`
--

CREATE TABLE `product` (
  `pid` int(11) NOT NULL,
  `name` varchar(70) DEFAULT NULL,
  `image` varchar(255) NOT NULL,
  `category` varchar(70) DEFAULT NULL,
  `price` int(11) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Dumping data for table `product`
--

INSERT INTO `product` (`pid`, `name`, `image`, `category`, `price`) VALUES
(1, 'Samsung Galaxy A10S', '1.jpg', 'Mobile', 520),
(2, 'HP Laptop - 17z-ca100 ', '2.jpg', 'Laptop', 1600),
(3, '3 IN 1 CAR VOLTMETER', '3.jpg', 'Car', 2020),
(4, 'Gucci G-Timeless', '4.jpg', 'Watch', 320),
(5, 'Infinix Hot S3', '5.jpg', 'Mobile', 150),
(6, 'VIVO V9 Youth', '6.jpeg', 'Laptop', 3500),
(7, 'Moto E4 Plus', '7.jpeg', 'Car', 250),
(8, 'Lenovo K8 Plus', '8.jpeg', 'Watch', 4500);

--
-- Indexes for dumped tables
--

--
-- Indexes for table `product`
--
ALTER TABLE `product`
  ADD PRIMARY KEY (`pid`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `product`
--
ALTER TABLE `product`
  MODIFY `pid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9;




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("/fetchrecords",methods=["POST","GET"])
def fetchrecords():
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    if request.method == 'POST':
        query = request.form['action']
        minimum_price = request.form['minimum_price']
        maximum_price = request.form['maximum_price']
        #print(query)
        if query == '':
            cur.execute("SELECT * FROM product ORDER BY pid ASC")
            productlist = cur.fetchall()
            print('all list')
        else:
            cur.execute("SELECT * FROM product WHERE price BETWEEN (%s) AND (%s)", [minimum_price, maximum_price])
            productlist = cur.fetchall()  
    return jsonify({'htmlresponse': render_template('response.html', productlist=productlist)})

if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html>
<head>
<title>Product Filters Price Range Using Python Flask 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" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<div class="container">
    <div class="row">
    <br />
    <h2 align="center">Product Filters Price Range Using Python Flask Mysql and Jquery Ajax</h2>
    <br />
		<div class="col-md-3">                				
			<div class="list-group">
				<h3>Price</h3>
				<input type="hidden" id="hidden_minimum_price" value="0" />
                <input type="hidden" id="hidden_maximum_price" value="65000" />
                <p id="price_show">10 - 5000</p>
                <div id="price_range"></div>
            </div>				
        </div>
		<div class="col-md-9">
           <div class="row filter_data">
        </div>
    </div>
    </div>
</div>
<style>
#loading
{
	text-align:center; 
	background: url('images/loading.gif') no-repeat center; 
	height: 150px;
}
</style>
<script>
$(document).ready(function(){
    filter_data();
    function filter_data()
    {
        $('.filter_data').html('<div id="loading" style="" ></div>');
        var action = 'fetch_data';
        var minimum_price = $('#hidden_minimum_price').val();
        var maximum_price = $('#hidden_maximum_price').val();
        $.ajax({
            url:"/fetchrecords",
            method:"POST",
            data:{action:action, minimum_price:minimum_price, maximum_price:maximum_price},
            success:function(data){
                $('.filter_data').html(data);
				$(".filter_data").append(data.htmlresponse);
            }
        });
    }
    $('#price_range').slider({
        range:true,
        min:50,
        max:5000,
        values:[50, 5000],
        step:50,
        stop:function(event, ui)
        {
            $('#price_show').html(ui.values[0] + ' - ' + ui.values[1]);
            $('#hidden_minimum_price').val(ui.values[0]);
            $('#hidden_maximum_price').val(ui.values[1]);
            filter_data();
        }
    });
});
</script>
</body>
</html>
templates/response.html
//templates/response.html
{% for row in productlist %}  
<div class="col-sm-4 col-lg-3 col-md-3">
    <div style="border:1px solid #ccc; border-radius:5px; padding:16px; margin-bottom:16px; height:300px;">
        <img src="/static/images/{{row.image}}" alt="" class="img-responsive" >
        <p align="center"><strong><a href="#">{{row.name}}</a></strong></p>
        <h4 style="text-align:center;" class="text-danger" >{{row.price}}</h4>
    </div>
</div>
{% endfor %} 

Wednesday, February 17, 2021

Jquery Ajax PHP Mysql File Upload Progress Bar

Jquery Ajax PHP Mysql File Upload Progress Bar

--
-- Table structure for table `uploads`
--

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

--
-- Dumping data for table `uploads`
--

INSERT INTO `uploads` (`id`, `file_name`, `upload_time`) VALUES
(1, 'car.jpg', '2021-02-17 08:10:47');

--
-- Indexes for dumped tables
--

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

--
-- AUTO_INCREMENT for dumped tables
--

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

jQuery Form Plugin allows you to easily and unobtrusively upgrade HTML forms to use AJAX.

https://github.com/jquery-form/form
bootstrap progressbar https://getbootstrap.com/docs/4.0/components/progress/
index.php
//index.php
<!DOCTYPE html>
<html>
<head>
<title>Jquery Ajax PHP Mysql File Upload Progress Bar</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>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.3.0/jquery.form.min.js" integrity="sha384-qlmct0AOBiA2VPZkMY3+2WqkHtIQ9lSdAsAn5RUJD/3vA5MKDgSGcdmIv4ycVxyn" crossorigin="anonymous"></script>
<!--<script src="/static/js/jquery.form.js"></script>-->
	</head>
	<body>
		<div class="container">
			<br />
			<h3 align="center">Jquery Ajax PHP Mysql File Upload Progress Bar</h3>
			<br />
			<div class="panel panel-default">
				<div class="panel-heading"><b>Jquery Ajax PHP Mysql File Upload Progress Bar</b></div>
				<div class="panel-body">
					<form id="uploadImage" action="upload.php" method="post">
						<div class="form-group">
							<label>File Upload</label>
							<input type="file" name="uploadFile" id="uploadFile" accept=".jpg, .png" />
						</div>
						<div class="form-group">
							<input type="submit" id="uploadSubmit" value="Upload" class="btn btn-info" />
						</div>
						<div class="progress">
							<div class="progress-bar progress-bar-striped bg-success" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
						</div>
						<div id="targetLayer" style="display:none;"></div>
					</form>
					<div id="loader-icon" style="display:none;"><img src="images/loader.gif" /></div>
				</div>
			</div>
		</div>
<script>
$(document).ready(function(){
	$('#uploadImage').submit(function(event){
		if($('#uploadFile').val())
		{
			event.preventDefault();
			$('#loader-icon').show();
			$('#targetLayer').hide();
			$(this).ajaxSubmit({
				target: '#targetLayer',
				beforeSubmit:function(){
					$('.progress-bar').width('50%');
				},
				uploadProgress: function(event, position, total, percentageComplete)
				{
					$('.progress-bar').animate({
						width: percentageComplete + '%'
					}, {
						duration: 1000
					});
				},
				success:function(){
					$('#loader-icon').hide();
					$('#targetLayer').show();
				},
				resetForm: true
			});
		}
		return false;
	});
});
</script>
</body>
</html>
upload.php
//upload.php
<?php
include('dbcon.php');
if(!empty($_FILES))
{
	if(is_uploaded_file($_FILES['uploadFile']['tmp_name']))
	{
		$source_path = $_FILES['uploadFile']['tmp_name'];
		$target_path = 'upload/' . $_FILES['uploadFile']['name'];
		if(move_uploaded_file($source_path, $target_path))
		{
			$filename = $_FILES['uploadFile']['name'];
			$today = date("Y-m-d h:i"); 
			$sql = "INSERT INTO uploads(file_name,upload_time) VALUES ('$filename','$today')"; 
			$conn->query($sql);
			echo '<p><b>File successfully uploaded '.$filename.' to the database!</b><p>'; 
			echo '<p><img src="'.$target_path.'" class="img-thumbnail" width="300" height="250" /></p>';
		}
	}
}
?>
dbcon.php
//dbcon.php
<?php
$conn = new mysqli('localhost','root','','testingdb');
if ($conn->connect_error) {
    die('Error : ('. $conn->connect_errno .') '. $conn->connect_error);
}
?>

Tuesday, February 16, 2021

File Upload Progress Bar using Python Flask JQuery Ajax and MySQL Database

File Upload Progress Bar using Python Flask JQuery Ajax and MySQL Database

--
-- Table structure for table `uploads`
--

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

--
-- Dumping data for table `uploads`
--

INSERT INTO `uploads` (`id`, `file_name`, `upload_time`) VALUES
(1, 'car.jpg', '2021-02-17 08:10:47');

--
-- Indexes for dumped tables
--

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

--
-- AUTO_INCREMENT for dumped tables
--

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

jQuery Form Plugin allows you to easily and unobtrusively upgrade HTML forms to use AJAX.


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
from werkzeug.utils import secure_filename
import os
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) 

app.config['UPLOAD_FOLDER'] = 'static/uploads'
  
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 index(): 
    return render_template('index.html')

@app.route("/upload",methods=["POST","GET"])
def upload():
    file = request.files['uploadFile']
    filename = secure_filename(file.filename)
    if file and allowed_file(file.filename):
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        filenameimage = file.filename

        today = datetime.today() 
        cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        cur.execute("INSERT INTO uploads (file_name,upload_time) VALUES (%s,%s)",[filenameimage,today])
        mysql.connection.commit()       
        cur.close()
        msg  = 'File successfully uploaded ' + file.filename + ' to the database!' 
    else:
        msg  = 'Invalid Uplaod only png, jpg, jpeg, gif' 
    return jsonify({'htmlresponse': render_template('response.html', msg=msg, filenameimage=filenameimage)})

if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html>
<head>
<title>File Upload Progress Bar using Python Flask 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>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.3.0/jquery.form.min.js" integrity="sha384-qlmct0AOBiA2VPZkMY3+2WqkHtIQ9lSdAsAn5RUJD/3vA5MKDgSGcdmIv4ycVxyn" crossorigin="anonymous"></script>
<!--<script src="/static/js/jquery.form.js"></script>-->
</head>
	<body>
		<div class="container">
			<br />
			<h3 align="center">File Upload Progress Bar using Python Flask JQuery Ajax and MySQL Database</h3>
			<br />
			<div class="panel panel-default">
				<div class="panel-heading"><b>Ajax File Upload Progress Bar using JQuery Ajax</b></div>
				<div class="panel-body">
					<form id="uploadImage" action="/upload" method="post">
						<div class="form-group">
							<label>File Upload</label>
							<input type="file" name="uploadFile" id="uploadFile" accept=".jpg, .png" />
						</div>
						<div class="form-group">
							<input type="submit" id="uploadSubmit" value="Upload" class="btn btn-info" />
						</div>
						<div class="progress">
							<div class="progress-bar progress-bar-striped bg-success" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
						</div>
						<div id="targetLayer" style="display:none;"></div>
					</form>
					<div id="loader-icon" style="display:none;"><img src="/static/images/loader.gif" /></div>
				</div>
			</div>
		</div>
<script>
$(document).ready(function(){
	$('#uploadImage').submit(function(event){
		if($('#uploadFile').val()){
			event.preventDefault();
			$('#loader-icon').show();
			$('#targetLayer').hide();
			$(this).ajaxSubmit({
				target: '#targetLayer',
				beforeSubmit:function(){
					$('.progress-bar').width('50%');
				},
				uploadProgress: function(event, position, total, percentageComplete)
				{
					$('.progress-bar').animate({
						width: percentageComplete + '%'
					}, {
						duration: 1000
					});
				},
				success:function(data){
					$('#loader-icon').hide();
					$('#targetLayer').show();
					$('#targetLayer').append(data.htmlresponse);
				},
				resetForm: true
			});
		}
		return false;
	});
});
</script>
</body>
</html>
templates/response.html
//templates/response.html
<p><b>{{ msg }}</b></p>
<img src="/static/uploads/{{ filenameimage }}" class="img-thumbnail" width="300" height="250" />

Monday, February 15, 2021

Python Flask Jquery Ajax Live Data Search Select Dropdown

Python Flask Jquery Ajax Live Data Search Select Dropdown

--
-- Table structure for table `employee`
--

CREATE TABLE `employee` (
  `id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `position` varchar(100) NOT NULL,
  `office` varchar(100) NOT NULL,
  `age` int(11) NOT NULL,
  `salary` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `employee`
--

INSERT INTO `employee` (`id`, `name`, `position`, `office`, `age`, `salary`) VALUES
(1, 'Caite Ednalan', 'Accountant', 'Tokyo', 36, 5689),
(2, 'Mark Oto Ednalan', 'Chief Executive Officer (CEO)', 'London', 56, 5648),
(3, 'Jacob thompson', 'Junior Technical Author', 'San Francisco', 23, 5689),
(4, 'cylde Ednalan', 'Software Engineer', 'Olongapo', 23, 54654),
(5, 'Angelica Ramos', 'Software Engineer', 'San Francisco', 26, 5465),
(6, 'Airi Satou', 'Integration Specialist', 'New York', 53, 56465),
(8, 'Tiger Nixon', 'Software Engineer', 'London', 45, 456),
(9, 'Airi Satou', 'Pre-Sales Support', 'New York', 25, 4568),
(10, 'Angelica Ramos', 'Sales Assistant', 'New York', 45, 456),
(11, 'Ashton updated', 'Senior Javascript Developer', 'Olongapo', 45, 54565),
(12, 'Bradley Greer', 'Regional Director', 'San Francisco', 27, 5485),
(13, 'Brenden Wagner', 'Javascript Developer', 'San Francisco', 38, 65468),
(14, 'Brielle Williamson', 'Personnel Lead', 'Olongapo', 56, 354685),
(15, 'Bruno Nash', 'Customer Support', 'New York', 36, 65465),
(16, 'cairocoders', 'Sales Assistant', 'Sydney', 45, 56465),
(17, 'Zorita Serrano', 'Support Engineer', 'San Francisco', 38, 6548),
(18, 'Zenaida Frank', 'Chief Operating Officer (COO)', 'San Francisco', 39, 545),
(19, 'Yuri Berry', 'Accountant', 'Tokyo', 38, 5468);

--
-- Indexes for dumped tables
--

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

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `employee`
--
ALTER TABLE `employee`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=20;
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():
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    cur.execute("SELECT DISTINCT office FROM employee ORDER BY office ASC")
    employee = cur.fetchall()  
    return render_template('index.html', employee = employee)

@app.route("/fetchrecords",methods=["POST","GET"])
def fetchrecords():
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    if request.method == 'POST':
        query = request.form['query']
        #print(query)
        if query == '':
            cur.execute("SELECT * FROM employee ORDER BY id DESC")
            employeelist = cur.fetchall()
            print('all list')
        else:
            search_text = request.form['query']
            print(search_text)
            cur.execute("SELECT * FROM employee WHERE office IN (%s) ORDER BY id DESC", [search_text])
            employeelist = cur.fetchall()  
    return jsonify({'htmlresponse': render_template('response.html', employeelist=employeelist)})

if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<title>Python Flask Jquery Ajax Live Data Search Select Dropdown</title>
		<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.6/js/bootstrap.min.js"></script>
		<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
	</head>
	<body>
		<div class="container">
			<br />
			<h2 align="center">Python Flask Jquery Ajax Live Data Search Select Dropdown</h2><br />
			<select name="search_filter" id="search_filter" class="form-control">
			<option value="">Select Option</option>';
			{% for row in employee %}
				<option value="{{row.office}}">{{row.office}}</option>';	
			{% endfor %}
			</select>
			<input type="hidden" name="hidden_value" id="hidden_value" />
			<div style="clear:both"></div>
			<br />
			<div class="table-responsive">
				<table class="table table-striped table-bordered">
					<thead>
						<tr>
							<th>Name</th>
							<th>Position</th>
							<th>Age</th>
							<th>Salary</th>
							<th>Office</th>
						</tr>
					</thead>
					<tbody>
					</tbody>
				</table>
			</div>
			<br />
			<br />
			<br />
		</div>
<script>
$(document).ready(function(){
	load_data();
	function load_data(query='')
	{
		$.ajax({
			url:"/fetchrecords",
			method:"POST",
			data:{query:query},
			success:function(data)
			{ 
				$('tbody').html(data);
				$('tbody').append(data.htmlresponse);
			}
		})
	}

	$('#search_filter').change(function(){
		$('#hidden_value').val($('#search_filter').val());
		var query = $('#hidden_value').val(); 
		load_data(query);
	});
	
});
</script>
</body>
</html>
templates/response.html
//templates/response.html
{% for row in employeelist %}  
<tr>
    <td>{{row.name}}</td>
    <td>{{row.position}}</td>
    <td>{{row.age}}</td>
    <td>{{ "$%.2f"|format(row.salary) }}</td>
    <td>{{row.office}}</td>
</tr>
{% endfor %} 

PHP Mysql and Jquery Ajax Data Live Search Multi Select Dropdown

PHP Mysql and Jquery Ajax Data Live Search Multi Select Dropdown

bootstrap-select
The jQuery plugin that brings select elements into the 21st century with intuitive multiselection, searching, and much more. 


--
-- Table structure for table `employee`
--

CREATE TABLE `employee` (
  `id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `position` varchar(100) NOT NULL,
  `office` varchar(100) NOT NULL,
  `age` int(11) NOT NULL,
  `salary` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `employee`
--

INSERT INTO `employee` (`id`, `name`, `position`, `office`, `age`, `salary`) VALUES
(1, 'Caite Ednalan', 'Accountant', 'Tokyo', 36, '5689'),
(2, 'Mark Oto Ednalan', 'Chief Executive Officer (CEO)', 'London', 56, '5648'),
(3, 'Jacob thompson', 'Junior Technical Author', 'San Francisco', 23, '5689'),
(4, 'cylde Ednalan', 'Software Engineer', 'Olongapo', 23, '54654'),
(5, 'Angelica Ramos', 'Software Engineer', 'San Francisco', 26, '5465'),
(6, 'Airi Satou', 'Integration Specialist', 'New York', 53, '56465'),
(8, 'Tiger Nixon', 'Software Engineer', 'London', 45, '456'),
(9, 'Airi Satou', 'Pre-Sales Support', 'New York', 25, '4568'),
(10, 'Angelica Ramos', 'Sales Assistant', 'New York', 45, '456'),
(11, 'Ashton updated', 'Senior Javascript Developer', 'Olongapo', 45, '54565'),
(12, 'Bradley Greer', 'Regional Director', 'San Francisco', 27, '5485'),
(13, 'Brenden Wagner', 'Javascript Developer', 'San Francisco', 38, '65468'),
(14, 'Brielle Williamson', 'Personnel Lead', 'Olongapo', 56, '354685'),
(15, 'Bruno Nash', 'Customer Support', 'New York', 36, '65465'),
(16, 'cairocoders', 'Sales Assistant', 'Sydney', 45, '56465'),
(17, 'Zorita Serrano', 'Support Engineer', 'San Francisco', 38, '6548'),
(18, 'Zenaida Frank', 'Chief Operating Officer (COO)', 'San Francisco', 39, '545'),
(19, 'Yuri Berry', 'Accountant', 'Tokyo', 38, '5468');

--
-- Indexes for dumped tables
--

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

--
-- AUTO_INCREMENT for dumped tables
--

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

index.php
//index.php
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<title>PHP Mysql and Jquery Ajax Data Live Search Multi Select Dropdown</title>
		<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.6/js/bootstrap.min.js"></script>
		<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
		<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">
		<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>
	</head>
	<body>
		<div class="container">
			<br />
			<h2 align="center">PHP Mysql and Jquery Ajax Data Live Search Multi Select Dropdown</h2><br />
			<select name="multi_search_filter" id="multi_search_filter" multiple class="form-control selectpicker">
			<?php
			include('dbcon.php');
			$query = $conn->query("SELECT DISTINCT office FROM employee ORDER BY office ASC");
			while ($row = $query ->fetch_object()) {
			$office = $row->office;
				echo '<option value="'.$office.'">'.$office.'</option>';	
			}
			?>
			</select>
			<input type="hidden" name="hidden_country" id="hidden_country" />
			<div style="clear:both"></div>
			<br />
			<div class="table-responsive">
				<table class="table table-striped table-bordered">
					<thead>
						<tr>
							<th>Name</th>
							<th>Position</th>
							<th>Age</th>
							<th>Salary</th>
							<th>Office</th>
						</tr>
					</thead>
					<tbody>
					</tbody>
				</table>
			</div>
			<br />
			<br />
			<br />
		</div>
<script>
$(document).ready(function(){
	load_data();
	function load_data(query='')
	{
		$.ajax({
			url:"fetch.php",
			method:"POST",
			data:{query:query},
			success:function(data)
			{
				$('tbody').html(data);
			}
		})
	}
	$('#multi_search_filter').change(function(){
		$('#hidden_country').val($('#multi_search_filter').val());
		var query = $('#hidden_country').val();
		load_data(query);
	});
});
</script>
</body>
</html>
fetch.php
//fetch.php
<?php
include('dbcon.php');
if($_POST["query"] != '') {
	$search_array = explode(",", $_POST["query"]); 
	$search_text = "'" . implode("', '", $search_array) . "'";
	$query = $conn->query("SELECT * FROM employee WHERE office IN (".$search_text.") ORDER BY id DESC");
}else{
	$query = $conn->query("SELECT * FROM employee ORDER BY id DESC");
}
$total_row = mysqli_num_rows($query);
$output = '';
if($total_row > 0)
{
	while ($row = $query ->fetch_object()) {
		$salary = number_format($row->salary);
		$output .= '
		<tr>
			<td>'.$row->name.'</td>
			<td>'.$row->position.'</td>
			<td>'.$row->age.'</td>
			<td>$ '.$salary.'</td>
			<td>'.$row->office.'</td>
		</tr>';
	}
}else{
	$output .= '
	<tr>
		<td colspan="5" align="center">No Data Found</td>
	</tr>
	';
}
echo $output;
?>
dbcon.php
//dbcon.php
<?php
$conn = new mysqli('localhost','root','','testingdb');
if ($conn->connect_error) {
    die('Error : ('. $conn->connect_errno .') '. $conn->connect_error);
}
?>

Saturday, February 13, 2021

Live voting System using PHP Mysql and jquery Ajax bootstrap progressbar

Live voting System using PHP Mysql and jquery Ajax bootstrap progressbar

--
-- Table structure for table `tblprogramming`
--

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

--
-- Dumping data for table `tblprogramming`
--

INSERT INTO `tblprogramming` (`id`, `title`) VALUES
(1, 'Flask'),
(2, 'Laravel'),
(3, 'React.js'),
(4, 'Express'),
(5, 'Django');

--
-- Indexes for dumped tables
--

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

--
-- AUTO_INCREMENT for dumped tables
--

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

--
-- Table structure for table `tbl_poll`
--

CREATE TABLE `tbl_poll` (
  `poll_id` int(11) NOT NULL,
  `web_framework` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tbl_poll`
--

INSERT INTO `tbl_poll` (`poll_id`, `web_framework`) VALUES
(8, 'Flask'),
(9, 'Flask'),
(10, 'Flask'),
(11, 'Express'),
(12, 'React.js'),
(13, 'Laravel'),
(14, 'Flask'),
(15, 'Flask'),
(16, 'Laravel'),
(17, 'Django'),
(18, 'Django'),
(19, 'Flask');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_poll`
--
ALTER TABLE `tbl_poll`
  ADD PRIMARY KEY (`poll_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_poll`
--
ALTER TABLE `tbl_poll`
  MODIFY `poll_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=20;
index.php
//index.php
<html>  
<head>  
<title>Live voting System using PHP Mysql and jquery Ajax bootstrap progressbar</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">  
<?php
 include('dbcon.php');
 $query = $conn->query("SELECT * FROM tblprogramming order by id asc");
?>
            <br />  
            <br />
			<br />
			<h2 align="center">Live voting System using PHP Mysql and jquery Ajax bootstrap progressbar</h2><br />
			<div class="row">
				<div class="col-md-6">
					<form method="post" id="poll_form">
						<h3>Which is Best Web Development Frameworks</h3>
						<br />
						<?php  while ($row = $query ->fetch_object()) { ?>
						<div class="radio">
							<label><h4><input type="radio" name="poll_option" class="poll_option" value="<?php echo $row->title; ?>" /> <?php echo $row->title; ?></h4></label>
						</div>
						<?php } ?>
						<br />
						<input type="submit" name="poll_button" id="poll_button" class="btn btn-primary" />
					</form>
					<br />
				</div>
				<div class="col-md-6">
					<br />
					<br />
					<br />
					<h4>Live Poll Result</h4><br />
					<div id="poll_result"></div>
				</div>
			</div>
			<br />
			<br />
			<br />
		</div>
<script>  
$(document).ready(function(){
	fetch_poll_data();
	function fetch_poll_data()
	{
		$.ajax({
			url:"polldata.php",
			method:"POST",
			success:function(data)
			{
				$('#poll_result').html(data);
			}
		});
	}
	$('#poll_form').on('submit', function(event){
		event.preventDefault();
		var poll_option = '';
		$('.poll_option').each(function(){
			if($(this).prop("checked"))
			{
				poll_option = $(this).val();
			}
		});
		if(poll_option != '')
		{
			$('#poll_button').attr('disabled', 'disabled');
			var form_data = $(this).serialize();
			$.ajax({
				url:"insert.php",
				method:"POST",
				data:form_data,
				success:function()
				{
					$('#poll_form')[0].reset();
					$('#poll_button').attr('disabled', false);
					fetch_poll_data();
					alert("Poll Submitted Successfully");
				}
			});
		}
		else
		{
			alert("Please Select Option");
		}
	});
});  
</script>
</body>  
</html>  
polldata.php
//polldata.php
<?php
include('dbcon.php');
$resulttotal = $conn->query("SELECT * FROM tbl_poll"); 
$total_poll_row = mysqli_num_rows($resulttotal);

$query = $conn->query("SELECT * FROM tblprogramming order by id asc");
$output = '';
while ($row = $query ->fetch_object()) {
		$title=$row->title; 
		$result = $conn->query("SELECT * FROM tbl_poll WHERE web_framework = '".$title."'"); 
		$row = $result->fetch_row();
		$total_row = mysqli_num_rows($result);
		$percentage_vote = round(($total_row/$total_poll_row)*100);
		$progress_bar_class = '';
		if($percentage_vote >= 40)
		{
			$progress_bar_class = 'progress-bar-success';
		}
		else if($percentage_vote >= 25 && $percentage_vote < 40)
		{
			$progress_bar_class = 'progress-bar-info';
		}
		else if($percentage_vote >= 10 && $percentage_vote < 25)
		{
			$progress_bar_class = 'progress-bar-warning';
		}
		else
		{
			$progress_bar_class = 'progress-bar-danger';
		}
		$output .= '
		<div class="row">
			<div class="col-md-2" align="right">
				<label>'.$title.'</label>
			</div>
			<div class="col-md-10">
				<div class="progress">
					<div class="progress-bar '.$progress_bar_class.'" role="progressbar" aria-valuenow="'.$percentage_vote.'" aria-valuemin="0" aria-valuemax="100" style="width:'.$percentage_vote.'%">
						'.$percentage_vote.' % programmer like <b>'.$title.'</b> PHP Framework
					</div>
				</div>
			</div>
		</div>
		
		';
}
echo $output;
?>
insert.php
//insert.php
<?php
include('dbcon.php');
if(isset($_POST["poll_option"]))
{
	$poll_option = $_POST["poll_option"];
    $sql = "INSERT INTO tbl_poll(web_framework) VALUES ('$poll_option')"; 
    $conn->query($sql);
}
?>
dbcon.php
//dbcon.php
<?php
$conn = new mysqli('localhost','root','','testingdb');
if ($conn->connect_error) {
    die('Error : ('. $conn->connect_errno .') '. $conn->connect_error);
}
?>

Live Poll System using Python Flask Mysql and Jquery ajax

Live Poll System using Python Flask Mysql and Jquery ajax

online voting system using Python Flask Mysql and Jquery ajax

--
-- Table structure for table `tblprogramming`
--

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

--
-- Dumping data for table `tblprogramming`
--

INSERT INTO `tblprogramming` (`id`, `title`) VALUES
(1, 'Flask'),
(2, 'Laravel'),
(3, 'React.js'),
(4, 'Express'),
(5, 'Django');

--
-- Indexes for dumped tables
--

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

--
-- AUTO_INCREMENT for dumped tables
--

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

--
-- Table structure for table `tbl_poll`
--

CREATE TABLE `tbl_poll` (
  `poll_id` int(11) NOT NULL,
  `web_framework` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tbl_poll`
--

INSERT INTO `tbl_poll` (`poll_id`, `web_framework`) VALUES
(8, 'Flask'),
(9, 'Flask'),
(10, 'Flask'),
(11, 'Express'),
(12, 'React.js'),
(13, 'Laravel'),
(14, 'Flask'),
(15, 'Flask'),
(16, 'Laravel'),
(17, 'Django'),
(18, 'Django'),
(19, 'Flask');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_poll`
--
ALTER TABLE `tbl_poll`
  ADD PRIMARY KEY (`poll_id`);

--
-- AUTO_INCREMENT for dumped tables
--

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

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

@app.route("/polldata",methods=["POST","GET"])
def polldata():
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)  
    query = "SELECT * from tbl_poll"
    cur.execute(query)
    total_poll_row = int(cur.rowcount) 
    cur.execute("SELECT * FROM tblprogramming ORDER BY id ASC")
    framework = cur.fetchall()  
    frameworkArray = []
    for row in framework:
        get_title = row['title']
        cur.execute("SELECT * FROM tbl_poll WHERE web_framework = %s", [get_title])
        row_poll = cur.fetchone()  
        total_row = cur.rowcount
        #print(total_row)
        percentage_vote = round((total_row/total_poll_row)*100)
        print(percentage_vote)
        if percentage_vote >= 40:
            progress_bar_class = 'progress-bar-success'
        elif percentage_vote >= 25 and percentage_vote < 40:   
            progress_bar_class = 'progress-bar-info'   
        elif percentage_vote >= 10 and percentage_vote < 25:
            progress_bar_class = 'progress-bar-warning'
        else:
            progress_bar_class = 'progress-bar-danger'
 
        frameworkObj = {
                'id': row['id'],
                'name': row['title'],
                'percentage_vote': percentage_vote,
                'progress_bar_class': progress_bar_class}
        frameworkArray.append(frameworkObj)
    return jsonify({'htmlresponse': render_template('response.html', frameworklist=frameworkArray)})

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

if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<html>  
<head>  
<title>Live Poll System using Python Flask 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>	
</head>  
    <body>  
        <div class="container">  
            <br />  <br />
			<h2 align="center">Live Poll System using Python Flask Mysql and Jquery ajax</h2><br />
			<div class="row">
				<div class="col-md-6">
					<form method="post" id="poll_form">
						<h3>Which is Best Web Development Frameworks</h3>
						<br />
						{% for row in webframework %}
						<div class="radio">
							<label><h4><input type="radio" name="poll_option" class="poll_option" value="{{row.title}}" /> {{row.title}}</h4></label>
						</div>
						{% endfor %}
						<br />
						<input type="submit" name="poll_button" id="poll_button" class="btn btn-primary" />
					</form>
					<br />
				</div>
				<div class="col-md-6">
					<br />
					<br />
					<h4>Live Poll Result</h4><br />
					<div id="poll_result"></div>
				</div>
			</div>
		</div>
<script>  
$(document).ready(function(){
	fetch_poll_data();
	function fetch_poll_data()
	{ 
    	var fetchall = 'all';
    	var dataString = 'fetchall='+ fetchall;
		$.ajax({
			url:"/polldata",
			method:"POST",
      		data: dataString,
			success:function(data)
			{
				$('#poll_result').html(data); 
        		$("#poll_result").append(data.htmlresponse);
			}
		});
	}
	$('#poll_form').on('submit', function(event){
		event.preventDefault();
		var poll_option = '';
		$('.poll_option').each(function(){
			if($(this).prop("checked"))
			{
				poll_option = $(this).val();
			}
		});
		if(poll_option != '')
		{
			$('#poll_button').attr('disabled', 'disabled');
			var form_data = $(this).serialize();
			$.ajax({
				url:"/insert",
				method:"POST",
				data:form_data,
				success:function()
				{
					$('#poll_form')[0].reset();
					$('#poll_button').attr('disabled', false);
					fetch_poll_data();
					alert("Poll Submitted Successfully");
				}
			});
		}
		else
		{
			alert("Please Select Option");
		}
	});
});  
</script>
</body>  
</html>  
templates/response.html
//templates/response.html
{% for row in frameworklist %}  
<div class="row">
    <div class="col-md-2" align="right">
        <label>{{row.name}}</label>
    </div>
    <div class="col-md-10">
        <div class="progress">
            <div class="progress-bar {{row.progress_bar_class}}" role="progressbar" aria-valuenow="{{row.percentage_vote}}" aria-valuemin="0" aria-valuemax="100" style="width:{{row.percentage_vote}}%">
                {{row.percentage_vote}} % programmer like <b>{{row.name}}</b> Web Framework
            </div>
        </div>
    </div>
</div>
{% endfor %} 

Friday, February 12, 2021

PHP Mysql Image Crop & Upload using JQuery Ajax

PHP Mysql Image Crop & Upload using JQuery Ajax

Croppie
Croppie is a fast, easy to use image cropping plugin with tons of configuration options!


--
-- Table structure for table `uploads`
--

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

--
-- Dumping data for table `uploads`
--

INSERT INTO `uploads` (`id`, `file_name`, `upload_time`) VALUES
(1, '1613121943.jpg', '2021-02-12 10:25:43');

--
-- Indexes for dumped tables
--

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

--
-- AUTO_INCREMENT for dumped tables
--

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


index.php
//index.php
<!DOCTYPE html>
<html>
 <head>
  <title>PHP Mysql Image Crop & Upload using 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>
<script src="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.5/croppie.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.5/croppie.min.css" />
</head>
<body>  
        <div class="container">
          <br /> 
      <h3 align="center">PHP Mysql Image Crop & Upload using JQuery Ajax</h3>
      <br />
      <br />
   <div class="panel panel-default">
      <div class="panel-heading">Select Profile Image</div>
      <div class="panel-body" align="center">
       <input type="file" name="upload_image" id="upload_image" accept="image/*" />
       <br />
       <div id="uploaded_image"></div>
      </div>
     </div>
    </div>

<div id="uploadimageModal" class="modal" role="dialog">
 <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">Upload & Crop Image</h4>
        </div>
        <div class="modal-body">
          <div class="row">
       <div class="col-md-8 text-center">
        <div id="image_demo" style="width:350px; margin-top:30px"></div>
       </div>
       <div class="col-md-4" style="padding-top:30px;">
        <br />
        <br />
        <br/>
        <button class="btn btn-success crop_image">Crop & Upload Image</button>
     </div>
    </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(){

 $image_crop = $('#image_demo').croppie({
    enableExif: true,
    viewport: {
      width:200,
      height:200,
      type:'square' //circle
    },
    boundary:{
      width:300,
      height:300
    }
  });

  $('#upload_image').on('change', function(){
    var reader = new FileReader();
    reader.onload = function (event) {
      $image_crop.croppie('bind', {
        url: event.target.result
      }).then(function(){
        console.log('jQuery bind complete');
      });
    }
    reader.readAsDataURL(this.files[0]);
    $('#uploadimageModal').modal('show');
  });

  $('.crop_image').click(function(event){
    $image_crop.croppie('result', {
      type: 'canvas',
      size: 'viewport'
    }).then(function(response){
      $.ajax({
        url:"upload.php",
        type: "POST",
        data:{"image": response},
        success:function(data)
        {
          $('#uploadimageModal').modal('hide');
          $('#uploaded_image').html(data);
        }
      });
    })
  });

});  
</script>
 </body>
</html>
upload.php
<?php
//upload.php
include('dbcon.php');
if(isset($_POST["image"]))
{
 $data = $_POST["image"];
 $img_array_1 = explode(";", $data);
 $img_array_2 = explode(",", $img_array_1[1]);
 $basedecode = base64_decode($img_array_2[1]);
 $filename = time() . '.jpg';
 file_put_contents("upload/$filename", $basedecode);
 //file_put_contents($filename, $basedecode);
 echo '<img src="'.$filename.'" class="img-thumbnail" />';
 $now = date("Y-m-d H:i:s");
 $sql = "INSERT INTO uploads(file_name, upload_time) VALUES ('$filename','$now')"; 
 $conn->query($sql); 
}
?>
//dbcon.php
<?php
$conn = new mysqli('localhost','root','','testingdb');
if ($conn->connect_error) {
    die('Error : ('. $conn->connect_errno .') '. $conn->connect_error);
}
?>

Sunday, February 7, 2021

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

Jquery Fullcalandar CRUD(Create, Read, Update, Delete) with PHP 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;
index.php
//index.php
<!DOCTYPE html>
<html>
 <head>
  <title>Jquery Fullcalandar CRUD(Create, Read, Update, Delete) with PHP Jquery Ajax 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>
<?php
include('dbcon.php');
$query = $conn->query("SELECT * FROM events ORDER BY id");
?>
  <script>
    $(document).ready(function() {
     var calendar = $('#calendar').fullCalendar({
      editable:true,
      header:{
       left:'prev,next today',
       center:'title',
       right:'month,agendaWeek,agendaDay'
      },
      events: [<?php while ($row = $query ->fetch_object()) { ?>{ id : '<?php echo $row->id; ?>', title : '<?php echo $row->title; ?>', start : '<?php echo $row->start_event; ?>', end : '<?php echo $row->end_event; ?>', }, <?php } ?>],
      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.php",
        type:"POST",
        data:{title:title, start:start, end:end},
        success:function(data)
        {
          calendar.fullCalendar('refetchEvents');
          alert("Added Successfully");
          window.location.replace("calendar.php");
        }
        })
      }
      },

      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.php",
        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.php",
        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:"delete.php",
        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 PHP Jquery Ajax and Mysql</a></h2>
  <br />
  <div class="container">
    <div id="calendar"></div>
   </div>
 </body>
</html>
dbcon.php
//dbcon.php
<?php
$conn = new mysqli('localhost','root','','testingdb');
if ($conn->connect_error) {
    die('Error : ('. $conn->connect_errno .') '. $conn->connect_error);
}
?>
insert.php
//insert.php
<?php
include('dbcon.php');
if(isset($_POST["title"]))
{
	$title = $_POST['title'];
    $start = $_POST['start'];
    $end = $_POST['end'];
    $sql = "INSERT INTO events(title, start_event, end_event) VALUES ('$title','$start','$end')"; 
    $conn->query($sql); 
}
?>
update.php
//update.php
<?php
include('dbcon.php');
if(isset($_POST["id"]))
{
	$title = $_POST['title'];
    $start = $_POST['start'];
    $end = $_POST['end'];
    $id = $_POST['id'];
    $sql = "UPDATE events SET title='$title', start_event='$start', end_event='$end' WHERE id = $id"; 
    $conn->query($sql); 
}
?>
//delete.php
<?php
include('dbcon.php');
if(isset($_POST["id"]))
{
	$id = $_POST['id'];
    $sql = "DELETE FROM events WHERE id = $id"; 
    $conn->query($sql);
}	
?>

Related Post