article

Monday, November 30, 2020

Python Flask Drag and Drop Reorder with Jquery Ajax Jquery-UI and MySQLdb Database

Python Flask Drag and Drop Reorder with Jquery Ajax Jquery-UI and MySQLdb Database

Create Database Table
CREATE TABLE `gallery` (
  `id` int(11) NOT NULL,
  `photoname` varchar(255) NOT NULL,
  `display_order` int(5) NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL,
  `status` enum('1','0','','') NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

drag and drop reorder allows users to reorder element by drag and drop on desired position

app.py
#app.py
from flask import Flask, render_template, jsonify, request
from flask_mysqldb import MySQL,MySQLdb #pip install flask-mysqldb https://github.com/alexferl/flask-mysqldb
 
app = Flask(__name__)
   
app.secret_key = "caircocoders-ednalan-2020"
   
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'testingdb'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
mysql = MySQL(app)
 

@app.route('/')
def main():
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    result = cur.execute("SELECT * FROM gallery ORDER BY display_order")
    gallery = cur.fetchall()
    return render_template('drop_and_drop_reorder.html', gallery=gallery)
     
@app.route("/orderupdate",methods=["POST","GET"])
def orderupdate():
    cursor = mysql.connection.cursor()
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)	
    if request.method == 'POST':
        number_of_rows= cur.execute("SELECT * FROM gallery")	
        print(number_of_rows) #4		
        getorder = request.form['order']	
        order = getorder.split(",", number_of_rows)
        count=0		
        for value in order:
            count +=1
            #print(count)						
            cur.execute("UPDATE gallery SET display_order = %s WHERE id = %s ", [count, value])
            mysql.connection.commit()       
        cur.close()
    return jsonify(order)
	
if __name__ == '__main__':
    app.run(debug=True)
templates/drop_and_drop_reorder.html
//templates/drop_and_drop_reorder.html
<html>  
 <head>  
  <title>Python Flask Drag and Drop Reorder with Jquery Ajax Jquery-UI and MySQLdb Database</title>  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<style>
.gallery{ width:100%; float:left;}
.gallery ul{ margin:0; padding:0; list-style-type:none;}
.gallery ul li{ padding:7px; border:2px solid #ccc; float:left; margin:10px 7px; background:none; width:auto; height:auto;}
.gallery img{ width:250px;}
</style>
 </head>  
 <body> 
<div class="container">
	<h2>Python Flask Drag and Drop Reorder with Jquery Ajax Jquery-UI and MySQLdb Database</h2>
	<div>		
		<div class="gallery">
			<ul class="reorder-gallery">
			{% for row in gallery %}
				<li id="{{row.id}}" class="ui-sortable-handle"><a href="javascript:void(0);"><img src="/static/images/{{row.photoname}}" alt=""></a></li>
			{% endfor %}
			</ul>
		</div>
	</div><div id="test"></div>
</div>
<script>
$(document).ready(function(){	
	$("ul.reorder-gallery").sortable({		
		update: function( event, ui ) {
			updateOrder();
		}
	});  
});
function updateOrder() {	
	var item_order = new Array();
	$('ul.reorder-gallery li').each(function() {
		item_order.push($(this).attr("id"));
	}); 
	var order_string = 'order='+item_order;
	$.ajax({
		method: "POST",
		url: "/orderupdate",
		data: order_string,
		cache: false,
		success: function(data){	
			$("#test").html(data);
		}
	});
}
</script>	
 </body>  
</html>   

jQuery Ajax Drag and Drop Reorder with PHP and MySQL

jQuery Ajax Drag and Drop Reorder with PHP and MySQL


Create Database Table
CREATE TABLE `gallery` (
  `id` int(11) NOT NULL,
  `photoname` varchar(255) NOT NULL,
  `display_order` int(5) NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL,
  `status` enum('1','0','','') NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
//drag_and_drop_re_order.php
<html>  
 <head>  
  <title>jQuery Ajax Drag and Drop Reorder with PHP and MySQL</title>  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<style>
.gallery{ width:100%; float:left;}
.gallery ul{ margin:0; padding:0; list-style-type:none;}
.gallery ul li{ padding:7px; border:2px solid #ccc; float:left; margin:10px 7px; background:none; width:auto; height:auto;}
.gallery img{ width:250px;}
</style>
 </head>  
 <body> 
<div class="container">
	<h2>jQuery Ajax Drag and Drop Reorder with PHP and MySQL</h2>
	<div>		
		<div class="gallery">
			<ul class="reorder-gallery">
			<?php 		
include_once("db_connect.php");			
			$sql_query = "SELECT id, photoname FROM gallery ORDER BY display_order";
			$resultset = mysqli_query($conn, $sql_query) or die("database error:". mysqli_error($conn));
			$data_records = array();
			while( $row = mysqli_fetch_assoc($resultset)) {				
			?>
				<li id="<?php echo $row['id']; ?>" class="ui-sortable-handle"><a href="javascript:void(0);"><img src="img/<?php echo $row['photoname']; ?>" alt=""></a></li>
			<?php } ?>
			</ul>
		</div>
	</div><div id="test"></div>
</div>
<script>
$(document).ready(function(){	
	$("ul.reorder-gallery").sortable({		
		update: function( event, ui ) {
			updateOrder();
		}
	});  
});
function updateOrder() {	
	var item_order = new Array();
	$('ul.reorder-gallery li').each(function() {
		item_order.push($(this).attr("id"));
	}); 
	var order_string = 'order='+item_order;
	$.ajax({
		type: "GET",
		url: "order_update.php",
		data: order_string,
		cache: false,
		success: function(data){	
			$("#test").html(data);
		}
	});
}
</script>	
 </body>  
</html>  
db_connect.php
//db_connect.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testingdb";
$conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}
?>
order_update.php
//order_update.php
<?php 
include_once("db_connect.php");
if(isset($_GET["order"])) {
	$order  = explode(",",$_GET["order"]); 
	for($i=0; $i < count($order);$i++) {
		echo $order[$i]; echo "<br/>";
		$sql = "UPDATE gallery SET display_order='" . $i . "' WHERE id=". $order[$i];		
		mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));	
	}
}
?>

Saturday, November 28, 2020

Python Flask Add Remove Input Fields Dynamically with jQuery and save to database MySQLdb

Python Flask Add Remove Input Fields Dynamically with jQuery and save to database MySQLdb

In this tutorial user can add remove input fields and submit form to use input fields values and save to database using mysqldb

install mysqldb
pip install flask-mysqldb https://github.com/alexferl/flask-mysqldb

--
-- Table structure for table `fullnames`
--

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

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

app = Flask(__name__)
  
app.secret_key = "caircocoders-ednalan-2020"
  
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'testingdb'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
mysql = MySQL(app)
      
@app.route('/', methods=['GET', 'POST'])
def index():
    cursor = mysql.connection.cursor()
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    message = ''	
    if request.method == 'POST':
        fullname = request.form.getlist('field[]')
        for value in fullname:	
            cur.execute("INSERT INTO fullnames (full_name) VALUES (%s)",[value])
            mysql.connection.commit()		
        cur.close()
        message = "Succesfully Register"
    return render_template('index.html', message=message)
 

if __name__ == '__main__':
    app.run(debug=True)
templates/index.html
//templates/index.html
<html>  
 <head>  
  <title>Python Flask Add Remove Input Fields Dynamically with jQuery and save to database MySQLdb</title>  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<style>
.input-wrapper div {
    margin-bottom: 10px;
}
.remove-input {
    margin-top: 10px;
    margin-left: 15px;
    vertical-align: text-bottom;
}
.add-input {
    margin-top: 10px;
    margin-left: 10px;
    vertical-align: text-bottom;
}
</style>
 </head>  
 <body>  
  <div style="width:85%;padding:50px;">  
	<h2>Python Flask Add Remove Input Fields Dynamically with jQuery and save to database MySQLdb</h2>	
	{% if message %}
          <div class="alert alert-success">{{message}}</div>
    {% endif %}
	<form method="POST">
		<div class="input-wrapper">
			<div>Name : <br/>
			<input type="text" name="field[]" value=""/>
			<a href="javascript:void(0);" class="add-input" title="Add input"><img src="/static/img/add.png"/></a>
			</div>
		</div>
		<input type="submit" name="cmdsubmit">
	</form>
  
  </div>  
<script>
$(document).ready(function(){
    var max_input_fields = 10;
    var add_input = $('.add-input');
    var input_wrapper = $('.input-wrapper');
    var new_input = '<div><input type="text" name="field[]" value=""/><a href="javascript:void(0);" class="remove-input" title="Remove input"><img src="/static/img/remove.png"/></a></div>';
    var add_input_count = 1; 
	$(add_input).click(function(){
        if(add_input_count < max_input_fields){
            add_input_count++; 
            $(input_wrapper).append(new_input); 
        }
    });
	$(input_wrapper).on('click', '.remove-input', function(e){
        e.preventDefault();
        $(this).parent('div').remove();
        add_input_count--;
    });
});
</script>
 </body>  
</html>  

Add Remove Input Fields Dynamically with jQuery and PHP MySQLi


Add Remove Input Fields Dynamically with jQuery and PHP MySQLi

The tutorial, a user can add remove input fields and submit form to use input fields values and save to database using php mysqli

dynamic_addremove_textfields.php
//dynamic_addremove_textfields.php
<html>  
 <head>  
  <title>Add Remove Input Fields Dynamically with jQuery and PHP MySQLi</title>  
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<style>
.input-wrapper div {
    margin-bottom: 10px;
}
.remove-input {
    margin-top: 10px;
    margin-left: 15px;
    vertical-align: text-bottom;
}
.add-input {
    margin-top: 10px;
    margin-left: 10px;
    vertical-align: text-bottom;
}
</style>
 </head>  
 <body>  
<?php
$conn = new mysqli('localhost','root','','testingdb');
if ($conn->connect_error) {
    die('Error : ('. $conn->connect_errno .') '. $conn->connect_error);
}

if(isset($_POST["cmdaddnew"])){
	$fields  = $_POST['field'];
	foreach ($fields as $value) {
		//echo $value . " <br/>";
		 $sql = "INSERT INTO fullnames (full_name) VALUES ('".$value."')";
		 if ($conn->query($sql) === TRUE) {
		 echo "<h2>New record created successfully</h2>";
		 } else {
			echo "<h2>Error:</h2>";
		 }
	}
}
?>
  <div style="width:85%;padding:50px;">  
	<h2>Add Remove Input Fields Dynamically with jQuery and PHP MySQLi</h2>	
	<form action="" method="post">
		<div class="input-wrapper">
			<div>Name : <br/>
			<input type="text" name="field[]" value=""/>
			<a href="javascript:void(0);" class="add-input" title="Add input"><img src="img/add.png"/></a>
			</div>
		</div>
		<input type="submit" name="cmdaddnew" value="Submit"/>
	</form>
  
  </div>  
<script>
$(document).ready(function(){
    var max_input_fields = 10;
    var add_input = $('.add-input');
    var input_wrapper = $('.input-wrapper');
    var new_input = '<div><input type="text" name="field[]" value=""/><a href="javascript:void(0);" class="remove-input" title="Remove input"><img src="img/remove.png"/></a></div>';
    var add_input_count = 1; 
	$(add_input).click(function(){
        if(add_input_count < max_input_fields){
            add_input_count++; 
            $(input_wrapper).append(new_input); 
        }
    });
	$(input_wrapper).on('click', '.remove-input', function(e){
        e.preventDefault();
        $(this).parent('div').remove();
        add_input_count--;
    });
});
</script>
 </body>  
</html>  

Monday, November 23, 2020

Jquery Ajax Pagination with PHP and MySQLi

Jquery Ajax Pagination with PHP and MySQLi


//ajax_pagination.php
<html>  
 <head>  
  <title>Jquery Ajax Pagination with PHP and MySQLi</title>  
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
 <style>
.pagination{
	float:left;
	width:100%;
}
.botoom_link{
	float:left;
	width:100%;
}
.content{
float:left;
	width:100%;
}
ul {
    list-style: none;
	float:left;
	margin:0;
    padding: 0;
}
li{
	list-style: none;
	float: left;
	margin-right: 16px;
	padding:5px;
	border:solid 1px #dddddd;
	color:#0063DC;
}
li:hover{
	color:#FF0084;
	cursor: pointer;
}


</style> 
 </head>  
 <body>   
  <div style="width:85%;">  
	<h2>Jquery Ajax Pagination with PHP and MySQLi</h2>	
	<div class="row">
	<?php
	include("db_connect.php");
	$per_page = 20;
	$sql = "SELECT * FROM country";
	$result = mysqli_query($conn, $sql);
	$count = mysqli_num_rows($result);
	$pages = ceil($count/$per_page)
	?>		
    <div id="loading"><img src="images/loading.gif"/></div>
	<div id="content_container"></div>
	<div class="pagination" style="padding:10px;">
		<ul id="paginate">
			<?php		
			for($i=1; $i<=$pages; $i++)	{
				echo '<li id="'.$i.'">'.$i.'</li>';
			}
			?>
		</ul>
	</div>
	</div>
  
  </div>  
<script>
$(document).ready(function(){	
	function hideLoading() {
		$("#loading").fadeOut('slow');
	};	
	$("#paginate li:first").css({'color' : '#FF0084'}).css({'border' : 'none'});
	$("#content_container").load("ajaxpagination.php?page=1", hideLoading());
	$("#paginate li").click(function(){		
		$("#paginate li").css({'border' : 'solid #dddddd 1px'}).css({'color' : '#0063DC'});
		$(this).css({'color' : '#FF0084'}).css({'border' : 'none'});
		var page_num = this.id;
		$("#content_container").load("ajaxpagination.php?page=" + page_num, hideLoading());
	});
});
</script>
 </body>  
</html>  
db_connect.php
//db_connect.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testingdb";
$conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}
?>
ajaxpagination.php
//ajaxpagination.php
<?php
include("db_connect.php");
$per_page = 20;
if(isset($_GET['page'])) {
	$page=$_GET['page'];
}
$start = ($page-1)*$per_page;
$sql_query = "select * FROM country order by id limit $start,$per_page";
$resultset = mysqli_query($conn, $sql_query);
?>
<table width="100%">
	<thead>
		<tr>
		<th>   Id</th>
		<th>Country Name</th>			
		</tr>
	</thead>
	<?php
		while($rows = mysqli_fetch_array($resultset)){	?>	
			<tr bgcolor="#DDEBF5">
			<td>   <?php echo $rows['id']; ?></td>
			<td><?php echo $rows['country']; ?></td>
			</tr>
	<?php }	?>
</table>

Monday, November 16, 2020

Python Flask Dynamic Select Box and Sign Up using Mysql jsonify and javascript

Python Flask Dynamic Select Box and Sign Up using Mysql jsonify and javascript

install flask-mysqldb

pip install flask-mysqldb https://github.com/alexferl/flask-mysqldb

Database Table
CREATE TABLE countries (
id INTEGER PRIMARY KEY,
name STRING (60)

);

INSERT INTO countries (id, name) VALUES (171, 'Philippines');
INSERT INTO countries (id, name) VALUES (227, 'United States of America');

CREATE TABLE state (
id INTEGER PRIMARY KEY,
name STRING (60),
country_id INTEGER

);

INSERT INTO state (id, name, country_id) VALUES (1, 'ARMM', 171);
INSERT INTO state (id, name, country_id) VALUES (2, 'Bicol', 171);
INSERT INTO state (id, name, country_id) VALUES (3, 'Central Luzon', 171);
INSERT INTO state (id, name, country_id) VALUES (4, 'Central Mindanao', 171);
INSERT INTO state (id, name, country_id) VALUES (5, 'Alabama', 227);
INSERT INTO state (id, name, country_id) VALUES (6, 'Alaska', 227);
INSERT INTO state (id, name, country_id) VALUES (7, 'Arizona', 227);
INSERT INTO state (id, name, country_id) VALUES (8, 'California', 227);
INSERT INTO state (id, name, country_id) VALUES (9, 'Florida', 227);

CREATE TABLE city (
id INTEGER PRIMARY KEY,
state STRING (60),
name STRING (60),
stateid INTEGER

);

INSERT INTO city (id, state, name, stateid) VALUES (1, 'CA', 'Anaheim', 8);
INSERT INTO city (id, state, name, stateid) VALUES (2, 'NV', 'Arden-Arcade', 8);
INSERT INTO city (id, state, name, stateid) VALUES (3, 'CA', 'Bakersfield', 8);
INSERT INTO city (id, state, name, stateid) VALUES (4, 'CA', 'Carson', 8);
INSERT INTO city (id, state, name, stateid) VALUES (5, 'NV', 'Daly City', 8);
INSERT INTO city (id, state, name, stateid) VALUES (6, NULL, 'Angeles City', 3);
INSERT INTO city (id, state, name, stateid) VALUES (7, NULL, 'Olongapo', 3);
INSERT INTO city (id, state, name, stateid) VALUES (8, NULL, 'San Fernando', 3);
INSERT INTO city (id, state, name, stateid) VALUES (9, NULL, 'Tarlac', 3); 
app.py
 
#app.py
from flask import Flask, render_template, redirect, request, json, 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-2020"
  
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'testingdb'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
mysql = MySQL(app)
      
@app.route('/', methods=['GET', 'POST'])
def index():
    cursor = mysql.connection.cursor()
    query = "select * from country"
    cursor.execute(query)
    country = cursor.fetchall()
    message = ''	
    if request.method == 'POST':
        fullname = request.form['fullname']
        email = request.form['email']
        country = request.form['country']
        state = request.form['state']
        city = request.form['city']
        cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        cur.execute("INSERT INTO userflask (fullname, email, countryid, stateid, cityid) VALUES (%s,%s,%s,%s,%s)",(fullname,email,country,state,city))
        mysql.connection.commit()
        cur.close()
        message = "Succesfully Register"
    return render_template('index.html', country=country, message=message)
 
@app.route('/state/')
def statebycountry(get_state):
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    result = cur.execute("SELECT * FROM state WHERE country_id = %s", [get_state])
    state = cur.fetchall()	
    stateArray = []
    for row in state:
        stateObj = {
                'id': row['id'],
                'name': row['name']}
        stateArray.append(stateObj)
    return jsonify({'statecountry' : stateArray})
  
@app.route('/city/')
def city(get_city):
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    result = cur.execute("SELECT * FROM city WHERE stateid = %s", [get_city])
    state = cur.fetchall()	
    cityArray = []
    for row in state:
        cityObj = {
                'id': row['id'],
                'name': row['cityname']}
        cityArray.append(cityObj)
    return jsonify({'citylist' : cityArray})
	
if __name__ == '__main__':
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Python Flask Dynamic Select Box and Sign Up using Mysql jsonify and javascript</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
<div class="container">
 <div class="row">
    <div class="col-md-12">
    <p><h2>Python Flask Dynamic Select Box and Sign Up using Mysql jsonify and javascript</h2></p>
    {% if message %}
          <div class="alert alert-success">{{message}}</div>
    {% endif %}
    <form method="POST">
    <div class="form-group">
		<label for="email">Name:</label>
		<input type="text" class="form-control" name="fullname" id="fullname" placeholder="Your Name">
    </div> 
	<div class="form-group">
		<label for="email">Email:</label>
		<input type="email" class="form-control" name="email" id="email" placeholder="Your Email">
    </div>    
    <div class="form-group">
		<label for="email">Country:</label>
		<select class="form-control" id="country" name="country">
			{% for row in country %}
			<option value="{{row.id}}">{{row.country}}</option>
			{% endfor %}
		</select>
    </div>
    <div class="form-group">
		<label for="email">State:</label>
		<select class="form-control" id="state" name="state"></select>
    </div>
    <div class="form-group">
		<label for="email">City:</label>
		<select class="form-control" id="city" name="city"></select>
    </div>
    <input type="submit" class="btn btn-success btn-lg">
  </form> 
   </div>
 </div>
</div> 
<script>
country_select = document.getElementById('country');
state_select = document.getElementById('state');
city_select = document.getElementById('city');
 
country_select.onchange = function(){
 country = country_select.value;
 alert(country);
 fetch('state/' + country).then(function(response){
  response.json().then(function(data) {
   optionHTML = '';
   for (state of data.statecountry) {
    optionHTML += '<option value="' + state.id +'">' + state.name + '</option>'
   }
   state_select.innerHTML = optionHTML;
  });
 });
}
state_select.onchange = function(){
 city = state_select.value; 
 fetch('city/' + city).then(function(response){
  response.json().then(function(data) {
   optionHTML = '';
   for (city_rs of data.citylist) {
    optionHTML += '<option value="' + city_rs.id +'">' + city_rs.name + '</option>'
   }
   city_select.innerHTML = optionHTML;
  });
 });
}
</script>
</body>
</html>

Sunday, November 15, 2020

Flask MySQL jquery ajax Live Search


Flask MySQL jquery ajax Live Search app.py
 
#app.py
from flask import Flask,render_template,request,jsonify
from flask_mysqldb import MySQL
app = Flask(__name__)
mysql = MySQL(app)

#Enter here your database informations 
app.config["MYSQL_HOST"] = "localhost"
app.config["MYSQL_USER"] = "root"
app.config["MYSQL_PASSWORD"] = ""
app.config["MYSQL_DB"] = "testingdb"
app.config["MYSQL_CURSORCLASS"] = "DictCursor"

@app.route("/")
def index():
    return render_template("livesearch.html")
	
@app.route("/livesearch",methods=["POST","GET"])
def livesearch():
    searchbox = request.form.get("text")
    cursor = mysql.connection.cursor()
    query = "select * from country where country LIKE '{}%' order by country".format(searchbox)
    cursor.execute(query)
    result = cursor.fetchall()
    return jsonify(result)

if __name__ == "__main__":
    app.run(debug=True)
templates/livesearch.html
//templates/livesearch.html
<!DOCTYPE html>
<html>
<head>
<title>Flask MySQL jquery ajax Live Search</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
    $(document).ready(function(){
        $("#livebox").on("input",function(e){
            $("#datalist").empty();
            $.ajax({
                method:"post",
                url:"/livesearch",
                data:{text:$("#livebox").val()},
                success:function(res){
                    var data = "<div class='list-group'>";
                    $.each(res,function(index,value){
                        data += "<p class='list-group-item list-group-item-action'>"+value.country+"</p>";
                    });
                    data += "</div>";
                    $("#datalist").html(data);
                }
            });
        });
    });
</script>	
</head>
<body>
<div class="container">
	<br/>
	<p><h2>Flask MySQL jquery ajax Live Search</h2></p>
    <input type="text" id="livebox" name="text" class="form-control" placeholder="Find country" autocomplete="off">
    <p id = "datalist"></p>
</div>
</body>
</html>

Saturday, November 14, 2020

Live Username Available using PHP Mysqli and Jquery Ajax


Live Username Available using PHP Mysqli and Jquery Ajax

check username before inserting to database
check_username_availabilit.php
//check_username_availabilit.php
<html>  
 <head>  
  <title>Live Username Available using PHP Mysqli and Jquery Ajax</title>  
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
  <style>  
  body  
  {  
   margin:0;  
   padding:0;  
   background-color:#f1f1f1;  
  }  
  .box  
  {  
   width:800px;  
   border:1px solid #ccc;  
   background-color:#fff;  
   border-radius:5px;
   margin-top:36px;  
  }  
  </style>  
 </head>  
 <body>  
<?php   
include"dbcon.php";
$msg = "";
if(isset($_POST["register"]))
{
 $username = $_POST["username"];
 $txtemail = $_POST["txtemail"];
 $txtpass = $_POST["txtpass"];
 $sql = "INSERT INTO users(username, email, password) VALUES ('$username', '$txtemail', '$txtpass')"; 
 $conn->query($sql); 
 $msg = "Succesfully Register";
}
?> 
  <div class="container box">  
   <div class="form-group">  
    <h3 align="center">Live Username Available using PHP Mysqli and Jquery Ajax</h3><br />  
	<?php echo $msg; ?>
    <form class="form-signin" action="" method="post">
	<label>Enter Username</label>  
    <input type="text" name="username" id="username" class="form-control" />
    <span id="availability"></span>
    <br />
	<label>Enter Email</label>  
    <input type="text" name="txtemail" id="txtemail" class="form-control" />
	<label>Enter Password</label>  
    <input type="text" name="txtpass" id="txtpass" class="form-control" />
	<br />
    <button type="submit" name="register" class="btn btn-info" id="register" disabled>Register</button>
	</form>
    <br />
   </div>  
   <br />  
   <br />  
  </div>  
 </body>  
</html>  
<script>  
 $(document).ready(function(){  
   $('#username').blur(function(){

     var username = $(this).val();

     $.ajax({
      url:'check_username.php',
      method:"POST",
      data:{user_name:username},
      success:function(data)
      { //alert(data)
       if(data == '0')
       {
        $('#availability').html('<span class="text-danger">Username not available</span>');
        $('#register').attr("disabled", false);
       }
       else
       {
        $('#availability').html('<span class="text-success">Username Available</span>');
        $('#register').attr("disabled", true);
       }
      }
     })

  });
 });  
</script>
check_username.php
//check_username.php
<?php   
include"dbcon.php";
if(isset($_POST["user_name"]))
{
 $username = $_POST["user_name"];
 $query = "SELECT * FROM users WHERE username = '".$username."'";
 $result = mysqli_query($conn, $query);
 echo mysqli_num_rows($result);
}
?>
dbcon.php
//dbcon.php
<?php
$conn = new mysqli('localhost','root','','testingdb');
if ($conn->connect_error) {
    die('Error : ('. $conn->connect_errno .') '. $conn->connect_error);
}
?>

Live Username Available using Python Flask MongoDB and Jquery Ajax


Live Username Available using Python Flask MongoDB and Jquery Ajax

if you start registration it will ask your username if no record found in the database Username not available if username available the message display Username Available and the registration button is disable 
app.py
#app.py
from flask import Flask, render_template, flash, redirect, url_for, request, json
from flask_mongoengine import MongoEngine #ModuleNotFoundError: No module named 'flask_mongoengine' = (venv) C:\flaskmyproject>pip install flask-mongoengine  
 
app = Flask(__name__)

app.config['MONGODB_SETTINGS'] = {
    'db': 'dbmongocrud',
    'host': 'localhost',
    'port': 27017
}
db = MongoEngine()
db.init_app(app)	
  
class User(db.Document):
    user_name = db.StringField()
    email = db.StringField()
    password = db.StringField()
	
@app.route('/',methods=['POST','GET'])
def index():
    message = ''
    if request.method == 'POST':
        # Get Form Fields
        _username = request.form['username']
        txtemail = request.form['txtemail']
        txtpass = request.form['txtpass']
        usersave = User(user_name=_username, email=txtemail, password=txtpass)
        usersave.save()
        message = 'Succefully Register'
    return render_template('checkusername.html', message=message)
 
@app.route('/check_username', methods=['POST'])
def check_username():
    if request.method == 'POST':
        username = request.form['username']
        total = User.objects(user_name=username).count()
        print(username)
        if total > 0:
            msg =  '{ "html":"Ok"}'
            msghtml = json.loads(msg)
            return msghtml["html"] 
        else:	
            msg =  '{ "html":"No found"}'
            msghtml = json.loads(msg)
            return msghtml["html"] 
	
if __name__ == '__main__':
    app.run(debug=True)
templates/checkusername.html
//templates/checkusername.html
<html>  
 <head>  
  <title>Live Username Available using Python Flask MongoDB and Jquery Ajax</title>  
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
  <style>  
  body  
  {  
   margin:0;  
   padding:0;  
   background-color:#f1f1f1;  
  }  
  .box  
  {  
   width:800px;  
   border:1px solid #ccc;  
   background-color:#fff;  
   border-radius:5px;
   margin-top:36px;  
  }  
  </style>  
 <script>  
$(function() {
    $('#username').blur(function(){
		var username = $(this).val();
        $.ajax({
            url: '/check_username',
            data: $('form').serialize(),
            type: 'POST',
            success: function(response) {
                if(response == 'Ok'){
					$('#availability').html('<span class="text-success">Username Available</span>');
					$('#register').attr("disabled", true);
                }else{
					$('#availability').html('<span class="text-danger">Username not available</span>');
					$('#register').attr("disabled", false);
				}
            },
            error: function(error) {
                console.log(error);
            }
        });
    });
}); 
</script> 
 </head>  
 <body>  
  <div class="container box">  
   <div class="form-group">  
    <h3 align="center">Live Username Available using Python Flask MongoDB and Jquery Ajax</h3><br />  
	{% if message %}
          <div class="alert alert-success">{{message}}</div>
    {% endif %}
    <form class="form-signin" action="/" method="post">
	<label>Enter Username</label>  
    <input type="text" name="username" id="username" class="form-control" />
    <span id="availability"></span>
    <br />
	<label>Enter Email</label>  
    <input type="text" name="txtemail" id="txtemail" class="form-control" />
	<label>Enter Password</label>  
    <input type="text" name="txtpass" id="txtpass" class="form-control" />
	<br />
    <button type="submit" name="register" class="btn btn-info" id="register" disabled>Register</button>
	</form>
    <br />
   </div>  
   <br />  
   <br />  
  </div>  
 </body>  
</html>  

Crop image before upload and insert to database using PHP Mysqli and CropperJS

Crop image before upload and insert to database using PHP Mysqli and CropperJS

Cropper.js is a JavaScript library for cropping image.

With the Cropper.js, you can select an specific area of an image, and then upload the coordinates data to server-side to crop the image, or crop the image on browser-side directly.

https://fengyuanchen.github.io/cropperjs/
//crop_image_before_upload.php
<!DOCTYPE html>
<html>
<head>
<title>Crop image before upload and insert to database using PHP Mysqli and CropperJS </title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> 
<link rel="stylesheet" href="https://fengyuanchen.github.io/cropperjs/css/cropper.css" />
<script src="https://fengyuanchen.github.io/cropperjs/js/cropper.js"></script> 
<script>
$(document).ready(function(){
	var $modal = $('#modal_crop');
	var crop_image = document.getElementById('sample_image');
	var cropper;
	$('#upload_image').change(function(event){
		var files = event.target.files;
		var done = function(url){
			crop_image.src = url;
			$modal.modal('show');
		};
		if(files && files.length > 0)
		{
			reader = new FileReader();
			reader.onload = function(event)
			{
				done(reader.result);
			};
			reader.readAsDataURL(files[0]);
		}
	});
	$modal.on('shown.bs.modal', function() {
		cropper = new Cropper(crop_image, {
			aspectRatio: 1,
			viewMode: 3,
			preview:'.preview'
		});
	}).on('hidden.bs.modal', function(){
		cropper.destroy();
   		cropper = null;
	});
	$('#crop_and_upload').click(function(){
		canvas = cropper.getCroppedCanvas({
			width:400,
			height:400
		});
		canvas.toBlob(function(blob){
			url = URL.createObjectURL(blob);
			var reader = new FileReader();
			reader.readAsDataURL(blob);
			reader.onloadend = function(){
				var base64data = reader.result; 
				$.ajax({
					url:'crop_upload.php',
					method:'POST',
					data:{crop_image:base64data},
					success:function(data)
					{
						$modal.modal('hide'); 
					}
				});
			};
		});
	});
});
</script>
<style>
	img {
	  	display: block;
	  	max-width: 100%;
	}
	.preview {
		overflow: hidden;
		width: 160px; 
		height: 160px;
		margin: 10px;
		border: 1px solid red;
	}
	.modal-lg{
  		max-width: 1000px !important;
	}
</style>
</head>
	<body>
		<div class="container" align="center">
			<br />
			<h3 align="center">Crop image before upload and insert to database using PHP Mysqli and CropperJS</h3>
			<br />
			<div class="row">
			<form method="post">
				<input type="file" name="crop_image" class="crop_image" id="upload_image" />
			</form>
    		<div class="modal fade" id="modal_crop" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
			  	<div class="modal-dialog modal-lg" role="document">
			    	<div class="modal-content">
			      		<div class="modal-header">
			        		<h5 class="modal-title">Crop Image Before Upload</h5>
			        		<button type="button" class="close" data-dismiss="modal" aria-label="Close">
			          			<span aria-hidden="true">×</span>
			        		</button>
			      		</div>
			      		<div class="modal-body">
			        		<div class="img-container">
			            		<div class="row">
			                		<div class="col-md-8">
			                    		<img src="" id="sample_image" />
			                		</div>
			                		<div class="col-md-4">
			                    		<div class="preview"></div>
			                		</div>
			            		</div>
			        		</div>
			      		</div>
			      		<div class="modal-footer">
			      			<button type="button" id="crop_and_upload" class="btn btn-primary">Crop</button>
			        		<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
			      		</div>
			    	</div>
			  	</div>
			</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);
}
?>
crop_upload.php
//crop_upload.php
<?php
include"dbcon.php";
if(isset($_POST['crop_image']))
{
	$data = $_POST['crop_image'];
 	$image_array_1 = explode(";", $data);
	$image_array_2 = explode(",", $image_array_1[1]);
	$base64_decode = base64_decode($image_array_2[1]);
	$path_img = 'upload/'.time().'.png';
	$imagename = ''.time().'.png';
	file_put_contents($path_img, $base64_decode); 
    $sql2 = "INSERT INTO upload(imagename) VALUES ('$imagename')"; 
    $conn->query($sql2); 
}
?>

Thursday, November 12, 2020

Python Flask MongoDB Upload File and validate before save to Database


Python Flask MongoDB Upload File and validate before save to Database


app.py
 
#app.py
from flask import Flask, render_template, flash, redirect, url_for, request
from flask_mongoengine import MongoEngine #ModuleNotFoundError: No module named 'flask_mongoengine' = (venv) C:\flaskmyproject>pip install flask-mongoengine  
from werkzeug.utils import secure_filename
import os
#import magic
import urllib.request
 
app = Flask(__name__)
app.secret_key = "caircocoders-ednalan-2020"
 
app.config['MONGODB_SETTINGS'] = {
    'db': 'dbmongocrud',
    'host': 'localhost',
    'port': 27017
}
db = MongoEngine()
db.init_app(app)	
 
UPLOAD_FOLDER = 'static/img'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
  
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
  
def allowed_file(filename):
 return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
  
class User(db.Document):
    name = db.StringField()
    email = db.StringField()
    profile_pic = db.StringField()
	
@app.route('/')
def index():
    return render_template('upload.html')
 
@app.route('/upload', methods=['POST'])
def upload():
    file = request.files['inputFile']
    rs_username = request.form['txtusername']
    inputEmail = request.form['inputEmail']
    filename = secure_filename(file.filename)
  
    if file and allowed_file(file.filename):
       file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
       usersave = User(name=rs_username, email=inputEmail, profile_pic=file.filename)
       usersave.save()
       flash('File successfully uploaded ' + file.filename + ' to the database!')
       return redirect('/')
    else:
       flash('Invalid Uplaod only txt, pdf, png, jpg, jpeg, gif') 
    return redirect('/')    
  
if __name__ == '__main__':
    app.run(debug=True)
templates/upload.html
//templates/upload.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Python Flask MongoDB Upload File and validate before save to Database</title>
  </head>
  <body>
  <h2>Python Flask MongoDB Upload File and validate before save to Database </h2>
  <h3>Select a file to upload</h3>
        <p>
         {% with messages = get_flashed_messages() %}
           {% if messages %}
          {% for message in messages %}
            <div class="alert alert-primary">
             <strong>{{ message }}</strong>
           </div>
          {% endfor %}
           {% endif %}
         {% endwith %}
        </p>
<form method="post" action="/upload" enctype="multipart/form-data">
 <p>Name : <input type="text" name="txtusername" value="" placeholder="User Name" required> </p>
 <p>Email : <input type="email" name="inputEmail" placeholder="Email address" required></p>
  <p>
   <input type="file" name="inputFile" autocomplete="off" required onchange="loadFile(event)">
  </p>
    <p>
  <input type="submit" value="Submit">
 </p>
</form>
<img id="output" width="500"/>
<script>
  var loadFile = function(event) {
    var output = document.getElementById('output');
    output.src = URL.createObjectURL(event.target.files[0]);
    output.onload = function() {
      URL.revokeObjectURL(output.src) 
    }
  };
</script>

<style>
.alert-primary {
    color: #004085;
    background-color: #cce5ff;
    border-color: #b8daff;
}
.alert {
    position: relative;
    padding: .75rem 1.25rem;
    margin-bottom: 1rem;
    border: 1px solid transparent;
    border-radius: .25rem;
}
</style>
    </body>
</html>

Wednesday, November 11, 2020

Python Flask MongoDB Login Register logout with Jquery ajax and password hash

Python Flask MongoDB Login Register logout with Jquery ajax and password hash

MongoDB Compass Download https://www.mongodb.com/try/download/compass

create a file called app.py

ModuleNotFoundError: No module named 'flask_mongoengine'

install module flask_mongoengine
(venv) C:\flaskmyproject>pip install flask-mongoengine

create database table
table name user
name = StringField
email = StringField
password = StringField
reg_date = DateTimeField

app.py
#app.py
from flask import Flask, render_template, request, json, redirect, session
from flask_mongoengine import MongoEngine #ModuleNotFoundError: No module named 'flask_mongoengine' = (venv) C:\flaskmyproject>pip install flask-mongoengine
from werkzeug.security import generate_password_hash, check_password_hash
from datetime import datetime

app = Flask(__name__)
app.secret_key = "caircocoders-ednalan-2020"

app.config['MONGODB_SETTINGS'] = {
    'db': 'dbmongocrud',
    'host': 'localhost',
    'port': 27017
}
db = MongoEngine()
db.init_app(app)

class User(db.Document):
    name = db.StringField()
    email = db.StringField()
    password = db.StringField()
    reg_date = db.DateTimeField(datetime.now)
	
@app.route('/')
def main():
    return render_template('index.html')
	
@app.route('/signUp',methods=['POST','GET'])
def signUp():	
    today = datetime.today()	
    #print(today)
    if request.method == 'POST':
        _name = request.form['inputName']
        _email = request.form['inputEmail']
        _password = request.form['inputPassword']
        # validate the received values
        if _name and _email and _password:
            _hashed_password = generate_password_hash(_password)
            users = User.objects(email=_email).first()
            if not users:
                usersave = User(name=_name, email=_email, password=_hashed_password, reg_date=today)
                usersave.save()
                msg =  '{ "html":"ok"}'
                msghtml = json.loads(msg)
                return msghtml["html"]
            else:
                msg =  '{ "html":"

A user with this email address already exists

"}' msghtml = json.loads(msg) return msghtml["html"] else: msg = '{ "html":"

Enter the required fields

"}' msghtml = json.loads(msg) return msghtml["html"] else: return render_template("signup.html") @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': # Get Form Fields _username = request.form['inputEmail'] _password = request.form['inputPassword'] # Get user by username users = User.objects(email=_username).count() print(users) # result 1 if users > 0: # Get stored hash user_rs = User.objects(email=_username).first() password = user_rs['password'] print(password) # Compare Passwords if check_password_hash(password, _password): # Passed session['sessionusername'] = _username return redirect('/userHome') else: error = 'Invalid login' return render_template('signin.html', error=error) else: error = 'Username not found' return render_template('signin.html', error=error) return render_template('signin.html') @app.route('/userHome') def userHome(): print(session.get('sessionusername')) if session.get('sessionusername'): return render_template('userHome.html') else: return render_template('error.html',error = 'Unauthorized Access') @app.route('/logout') def logout(): session.pop('sessionusername', None) return redirect('/') if __name__ == '__main__': app.run(debug=True)
templates/signup.html
//templates/signup.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Python Flask MongoDB Login Register logout with Jquery ajax and password hash</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="/static/js/signUp.js"></script>
</head>
<body>
    <div class="container">
        <div class="header">
            <nav>
                <ul class="nav nav-pills pull-right">
                    <li role="presentation" class="active"><a href="/">Home</a></li>
                    <li role="presentation"><a href="/login">Sign In</a></li>
                    <li role="presentation"><a href="/signUp">Sign Up</a></li>
                </ul>
            </nav>
            <img src="/static/images/Flask_Icon.png" alt="Flask_Icon.png"/ > 
        </div>
      <div class="jumbotron">
        <h2>Python Flask MongoDB Login Register logout with Jquery ajax and password hash</h2>
        <div id="message"></div>
        <form class="form-signin">
        <p><label for="inputName" class="sr-only">Name</label>
        <input type="name" name="inputName" id="inputName" class="form-control" placeholder="Name" required autofocus></p>
        <p><label for="inputEmail" class="sr-only">Email address</label>
        <input type="email" name="inputEmail" id="inputEmail" class="form-control" placeholder="Email address" required autofocus></p>
        <p><label for="inputPassword" class="sr-only">Password</label>
        <input type="password" name="inputPassword" id="inputPassword" class="form-control" placeholder="Password" required></p>
        <p><button id="btnSignUp" class="btn btn-lg btn-primary btn-block" type="button">Sign up</button></p>
      </form>
      </div>
      <footer class="footer">
         <p>©tutorial101.blogspot.com</p>
      </footer>
    </div>
<style>
#message h3 {
	border:1px #a81b2f solid;padding:5px;
}
</style>	
  </body>
</html>
templates/signin.html
//templates/signin.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Python Flask MongoDB Login Register logout with Jquery ajax and password hash</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
    <div class="container">
        <div class="header">
            <nav>
                <ul class="nav nav-pills pull-right">
                    <li role="presentation" class="active"><a href="/">Home</a></li>
                    <li role="presentation"><a href="/login">Sign In</a></li>
                    <li role="presentation"><a href="/signUp">Sign Up</a></li>
                </ul>
            </nav>
            <img src="/static/images/Flask_Icon.png" alt="Flask_Icon.png"/ > 
        </div>
      <div class="jumbotron">
        <h2>Python Flask MongoDB Login Register logout with Jquery ajax and password hash</h2>
        {% if error %}
          <div class="alert alert-danger">{{error}}</div>
        {% endif %}
        <form class="form-signin" action="/login" method="post">
        <p><label for="inputEmail" class="sr-only">Email address</label>
        <input type="email" name="inputEmail" id="inputEmail" class="form-control" placeholder="Email address" required autofocus></p>
        <p><label for="inputPassword" class="sr-only">Password</label>
        <input type="password" name="inputPassword" id="inputPassword" class="form-control" placeholder="Password" required></p>
         
        <p><button id="btnSignIn" class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button></p>
      </form>
      </div>
        <footer class="footer">
            <p>©tutorial101.blogspot.com</p>
        </footer>
    </div>
  </body>
</html>
templates/userHome.html
//templates/userHome.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Login Register logout with Jquery ajax, json and MySQLdb and password hash</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
    <div class="container">
        <div class="header">
            <nav>
                <ul class="nav nav-pills pull-right">
                    <li role="presentation" class="active"><a href="/userHome">Dashboard</a></li>
                    <li role="presentation"><a href="/logout">Log Out</a></li>
                </ul>
            </nav>
            <img src="/static/images/Flask_Icon.png" alt="Flask_Icon.png"/ > 
        </div>
      <div class="jumbotron">
        <h1>Dashboard <small> Welcome {{session.sessionusername}}</small></h1>
      </div>      
        <footer class="footer">
            <p>©tutorial101.blogspot.com</p>
        </footer>
    </div>
</body>
</html>

templates/index.html
//templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Login Register logout with Jquery ajax, json and MySQLdb and password hash</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
    <div class="container">
        <div class="header">
            <nav>
                <ul class="nav nav-pills pull-right">
                    <li role="presentation" class="active"><a href="/">Home</a></li>
                    <li role="presentation"><a href="/login">Sign In</a></li>
                    <li role="presentation"><a href="/signUp">Sign Up</a></li>
                </ul>
            </nav>
            <img src="/static/images/Flask_Icon.png" alt="Flask_Icon.png"/ > 
        </div>
        <div class="jumbotron">
            <h2>Login Register logout with Jquery ajax, json and MySQLdb and password hash</h2>
            <p class="lead"></p>
            <p><a class="btn btn-lg btn-success" href="signUp" role="button">Sign Up</a>
            </p>
        </div>
        <div class="row marketing">
            <div class="col-lg-6">
                <h4>Blog 1</h4>
                <p>Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit</p>
            </div>
            <hr>
            <div class="col-lg-6">
                <h4>Blog 1</h4>
                <p>Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit</p>
            </div>
        </div>
        <footer class="footer">
            <p>©tutorial101.blogspot.com</p>
        </footer>
    </div>
</body>
</html>
static/js/signUp.js
//static/js/signUp.js
$(function() {
    $('#btnSignUp').click(function() {
        $.ajax({
            url: '/signUp',
            data: $('form').serialize(),
            type: 'POST',
            success: function(response) {
                console.log(response); alert(response)
				$('#message').html(response);
				if(response == 'ok'){
					window.location.href = '/login';
				}
            },
            error: function(error) {
                console.log(error);
				$('#message').html(error);
            }
        });
    });
});

Sunday, November 8, 2020

DataTable Inline Editing using Python Flask MongoDB CRUD (Create, Read, Update, Delete) with jquery ajax and X-Editable


DataTable Inline Editing using Python Flask MongoDB CRUD (Create, Read, Update, Delete) with jquery ajax and X-Editable

DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, built upon the foundations of progressive enhancement, that adds all of these advanced features to any HTML table.

https://datatables.net/

X-editable
This library allows you to create editable elements on your page. It can be used with any engine (bootstrap, jquery-ui, jquery only) and includes both popup and inline modes.

https://vitalets.github.io/x-editable/

ModuleNotFoundError: No module named 'flask_mongoengine'
Install
(venv) C:\flaskmyproject>pip install flask-mongoengine
app.py
 
#app.py
from flask import Flask, request, jsonify, render_template, json, redirect
from flask_mongoengine import MongoEngine #ModuleNotFoundError: No module named 'flask_mongoengine' = (venv) C:\flaskmyproject>pip install flask-mongoengine
from datetime import datetime

app = Flask(__name__)
app.config['MONGODB_SETTINGS'] = {
    'db': 'dbmongocrud',
    'host': 'localhost',
    'port': 27017
}
db = MongoEngine()
db.init_app(app)
 
class Employee(db.Document):
    name = db.StringField()
    email = db.StringField()
    phone = db.StringField()
    pub_date = db.DateTimeField(datetime.now)
	
@app.route('/')
def query_records():
    employee = Employee.objects.all()
    return render_template('useradmin.html', employee=employee)
 
@app.route('/updateemployee', methods=['POST'])
def updateemployee():
    pk = request.form['pk']
    namepost = request.form['name']
    value = request.form['value']
    employee_rs = Employee.objects(id=pk).first()
    if not employee_rs:
        return json.dumps({'error':'data not found'})
    else:
        if namepost == 'name':
            employee_rs.update(name=value)
        elif namepost == 'email':
            employee_rs.update(email=value)
        elif namepost == 'phone':
            employee_rs.update(phone=value)
    return json.dumps({'status':'OK'})
	
@app.route('/add', methods=['GET', 'POST'])
def create_record():
    txtname = request.form['txtname']
    txtemail = request.form['txtemail']
    txtphone = request.form['txtphone']
    employeesave = Employee(name=txtname, email=txtemail, phone=txtphone)
    employeesave.save()
    return redirect('/')

@app.route('/delete/', methods = ['POST','GET'])
def delete_employee(getid):
    print(getid)
    employeers = Employee.objects(id=getid).first()
    if not employeers:
        return jsonify({'error': 'data not found'})
    else:
        employeers.delete()	
    return redirect('/')
	
if __name__ == '__main__':
    app.run(debug=True)
templates/useradmin.html
//templates/useradmin.html
<html>
  <head>
    <meta name="viewport" content="width=device-width">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>DataTable Inline Editing using Python Flask MongoDB jquery ajax and X-Editable</title>
		<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
		<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
		<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>  
		<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />
		<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
		<link href="https://cdnjs.cloudflare.com/ajax/libs/x-editable/1.5.1/bootstrap3-editable/css/bootstrap-editable.css" rel="stylesheet">
  		<script src="https://cdnjs.cloudflare.com/ajax/libs/x-editable/1.5.1/bootstrap3-editable/js/bootstrap-editable.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function(){
	var dataTable = $('#sample_data').DataTable();
	$('#sample_data').editable({
		container:'body',
		selector:'td.name',
		url:'/updateemployee',
		title:'Name',
		type:'POST',
		validate:function(value){
			if($.trim(value) == '')
			{
				return 'This field is required';
			}
		}
	});

	$('#sample_data').editable({
		container:'body',
		selector:'td.email',
		url:'/updateemployee',
		title:'Email',
		type:'POST',
		validate:function(value){
			if($.trim(value) == '')
			{
				return 'This field is required';
			}
		}
	});

	$('#sample_data').editable({
		container:'body',
		selector:'td.phone',
		url:'/updateemployee',
		title:'Phone',
		type:'POST',
		validate:function(value){
			if($.trim(value) == '')
			{
				return 'This field is required';
			}
		}
	});
});	
function del(ID, title){
	if (confirm("Are you sure you want to delete '" + title + "'")){
		window.location.href = '/delete/' + ID;
	}
}
</script>
	</head>
	<body>
		<div class="container">
			<h3 align="center">DataTable Inline Editing using Python Flask MongoDB CRUD (Create, Read, Update, Delete) with jquery ajax and X-Editable</h3>
			<br />
			<div class="panel panel-default">
				<div class="panel-heading">
				<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
				  Add New Employee
				</button>
				</div>
				<div class="panel-body">
					<div class="table-responsive">
						<table id="sample_data" class="table table-bordered table-striped">
							<thead>
								<tr>
									<th>ID</th>
									<th>Name</th>
									<th>Email</th>
									<th>Phone</th>
									<th>Delete</th>
								</tr>
							</thead>
							<tbody>
								{% for row in employee %}
								<tr>
									<td data-pk="{{row.id}}">{{row.id}}</td>
									<td data-name="name" class="name" data-type="text" data-pk="{{row.id}}">{{row.name}}</td>
									<td data-name="email" class="email" data-type="text" data-pk="{{row.id}}">{{row.email}}</td>
									<td data-name="phone" class="phone" data-type="text" data-pk="{{row.id}}">{{row.phone}}</td>
									<td><a href="javascript:del('{{row.id}}','{{row.name}}')" class="btn btn-primary">Delete</a></td>
								</tr>
								{% endfor %}
							</tbody>
						</table>
					</div>
				</div>
			</div>
			
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Add New Employee</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">×</span>
        </button>
      </div>
      <div class="modal-body">
        <form role="form" method="post" action="/add">
          <div class="form-group">
            <label class="col-form-label">Name:</label>
            <input type="text" class="form-control" id="txtname" name="txtname">
          </div>
		  <div class="form-group">
            <label class="col-form-label">Email:</label>
            <input type="text" class="form-control" id="txtemail" name="txtemail">
          </div>
		  <div class="form-group">
            <label class="col-form-label">Phone:</label>
            <input type="text" class="form-control" id="txtphone" name="txtphone">
          </div>
		<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
		<input name="cmdsubmit" class="btn btn-primary" type="submit" value="Submit" />
        </form>
      </div>
    </div>
  </div>
</div>
		</div>
		<br />
		<br />
	</body>
</html>

Saturday, November 7, 2020

Python Flask How to convert mysql query result to json

Python Flask How to convert mysql query result to json
#app.py
from flask import Flask, json, 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-2020"
 
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'testingdb'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
mysql = MySQL(app)
 
@app.route('/')
def index():
   cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
   cur.execute("SELECT * FROM employee")
   rv = cur.fetchall()
   employee = []
   content = {}
   for result in rv:
       content = {'id': result['id'], 'name': result['name'], 'email': result['email']}
       employee.append(content)
       content = {}
   return jsonify(employee) 
   
       
if __name__ == '__main__':
    app.run(debug=True)

DataTable Inline Editing using Python Flask MySQLdb jquery ajax and X-Editable

 


DataTable Inline Editing using Python Flask MySQLdb jquery ajax and X-Editable

DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, built upon the foundations of progressive enhancement, that adds all of these advanced features to any HTML table.

https://datatables.net/

X-editable
This library allows you to create editable elements on your page. It can be used with any engine (bootstrap, jquery-ui, jquery only) and includes both popup and inline modes.

https://vitalets.github.io/x-editable/


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

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;

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

INSERT INTO `employee` (`id`, `name`, `email`, `phone`) VALUES
(1, 'Caite Ednalan', 'caite@gmail.com', '35465465'),
(2, 'Mark Oto', 'marokoto@gmail.com', '123123123'),
(3, 'Jacob thompson', 'jacobthomson@gmail.com', '13123123'),
(4, 'cylde Ednalan', 'cyledednalan@gmail.com', '313123'),
(5, 'Angelica Ramos', 'AngelicaRamos@gmail.com', '21654654654999999'),
(6, 'Airi Satou', 'AiriSatou@gmail.com', '354646'),
(8, 'Tiger Nixon', 'TigerNixon@gmail.com', '546456'),
(9, 'Airi Satou', 'AiriSatou@gmail.com', '354656'),
(10, 'Angelica Ramos', 'Caite@gmail.com', '465465465465'),
(11, 'Ashton Cox', 'marokoto@gmail.com', '123123123'),
(12, 'Bradley Greer', 'jacobthomson@gmail.com', '13123123'),
(13, 'Brenden Wagner', 'cyledednalan@gmail.com', '313123'),
(14, 'Brielle Williamson', 'AngelicaRamos@gmail.com', '21654654654999999'),
(15, 'Bruno Nash', 'AiriSatou@gmail.com', '354646');
app.py
#app.py
from flask import Flask, render_template, json, request, redirect
from flask_mysqldb import MySQL,MySQLdb #pip install flask-mysqldb https://github.com/alexferl/flask-mysqldb
from datetime import datetime
 
app = Flask(__name__)
 
app.secret_key = "caircocoders-ednalan-2020"
 
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'testingdb'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
mysql = MySQL(app)
 
@app.route('/')
def main():
    return redirect('/useradmin')
   
@app.route('/useradmin')
def useradmin():
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    result = cur.execute("SELECT * FROM employee")
    employee = cur.fetchall()
    return render_template('useradmin.html', employee=employee)

@app.route('/updateemployee', methods=['POST'])
def updateemployee():
        pk = request.form['pk']
        name = request.form['name']
        value = request.form['value']
        cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        if name == 'name':
           cur.execute("UPDATE employee SET name = %s WHERE id = %s ", (value, pk))
        elif name == 'email':
           cur.execute("UPDATE employee SET email = %s WHERE id = %s ", (value, pk))
        elif name == 'phone':
           cur.execute("UPDATE employee SET phone = %s WHERE id = %s ", (value, pk))
        mysql.connection.commit()
        cur.close()
        return json.dumps({'status':'OK'})
		    
if __name__ == '__main__':
    app.run(debug=True)
templates/useradmin.html
//templates/useradmin.html
<html>
  <head>
    <meta name="viewport" content="width=device-width">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>DataTable Inline Editing using Python Flask MySQLdb jquery ajax and X-Editable</title>
		<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
		<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
		<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>  
		<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />
		<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
		<link href="https://cdnjs.cloudflare.com/ajax/libs/x-editable/1.5.1/bootstrap3-editable/css/bootstrap-editable.css" rel="stylesheet">
  		<script src="https://cdnjs.cloudflare.com/ajax/libs/x-editable/1.5.1/bootstrap3-editable/js/bootstrap-editable.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function(){
	var dataTable = $('#sample_data').DataTable();
	$('#sample_data').editable({
		container:'body',
		selector:'td.name',
		url:'/updateemployee',
		title:'Name',
		type:'POST',
		validate:function(value){
			if($.trim(value) == '')
			{
				return 'This field is required';
			}
		}
	});

	$('#sample_data').editable({
		container:'body',
		selector:'td.email',
		url:'/updateemployee',
		title:'Email',
		type:'POST',
		validate:function(value){
			if($.trim(value) == '')
			{
				return 'This field is required';
			}
		}
	});

	$('#sample_data').editable({
		container:'body',
		selector:'td.phone',
		url:'/updateemployee',
		title:'Phone',
		type:'POST',
		validate:function(value){
			if($.trim(value) == '')
			{
				return 'This field is required';
			}
		}
	});
});	
</script>
	</head>
	<body>
		<div class="container">
			<h3 align="center">DataTable Inline Editing using Python Flask MySQLdb jquery ajax and X-Editable</h3>
			<br />
			<div class="panel panel-default">
				<div class="panel-heading">DataTable</div>
				<div class="panel-body">
					<div class="table-responsive">
						<table id="sample_data" class="table table-bordered table-striped">
							<thead>
								<tr>
									<th>ID</th>
									<th>Name</th>
									<th>Email</th>
									<th>Phone</th>
								</tr>
							</thead>
							<tbody>
								{% for row in employee %}
								<tr>
									<td data-pk="{{row.id}}">{{row.id}}</td>
									<td data-name="name" class="name" data-type="text" data-pk="{{row.id}}">{{row.name}}</td>
									<td data-name="email" class="email" data-type="text" data-pk="{{row.id}}">{{row.email}}</td>
									<td data-name="phone" class="phone" data-type="text" data-pk="{{row.id}}">{{row.phone}}</td>
								</tr>
								{% endfor %}
							</tbody>
						</table>
					</div>
				</div>
			</div>
		</div>
		<br />
		<br />
	</body>
</html>

DataTable Inline Editing using PHP Mysqli jquery ajax and X-Editable

DataTable InlineEditing using PHP Mysqli jquery ajax and X-Editable 

DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, built upon the foundations of progressive enhancement, that adds all of these advanced features to any HTML table.

https://datatables.net/

X-editable
This library allows you to create editable elements on your page. It can be used with any engine (bootstrap, jquery-ui, jquery only) and includes both popup and inline modes.

https://vitalets.github.io/x-editable/


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

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;

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

INSERT INTO `employee` (`id`, `name`, `email`, `phone`) VALUES
(1, 'Caite Ednalan', 'caite@gmail.com', '35465465'),
(2, 'Mark Oto', 'marokoto@gmail.com', '123123123'),
(3, 'Jacob thompson', 'jacobthomson@gmail.com', '13123123'),
(4, 'cylde Ednalan', 'cyledednalan@gmail.com', '313123'),
(5, 'Angelica Ramos', 'AngelicaRamos@gmail.com', '21654654654999999'),
(6, 'Airi Satou', 'AiriSatou@gmail.com', '354646'),
(8, 'Tiger Nixon', 'TigerNixon@gmail.com', '546456'),
(9, 'Airi Satou', 'AiriSatou@gmail.com', '354656'),
(10, 'Angelica Ramos', 'Caite@gmail.com', '465465465465'),
(11, 'Ashton Cox', 'marokoto@gmail.com', '123123123'),
(12, 'Bradley Greer', 'jacobthomson@gmail.com', '13123123'),
(13, 'Brenden Wagner', 'cyledednalan@gmail.com', '313123'),
(14, 'Brielle Williamson', 'AngelicaRamos@gmail.com', '21654654654999999'),
(15, 'Bruno Nash', 'AiriSatou@gmail.com', '354646');

editable_datatable.php
//editable_datatable.php
<html>
  <head>
    <meta name="viewport" content="width=device-width">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>DataTable Inline Editing using PHP Mysqli jquery ajax and X-Editable</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />		
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<link rel="stylesheet" href="https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css" />
<script src="https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js"></script>

<link href="https://cdnjs.cloudflare.com/ajax/libs/x-editable/1.5.1/bootstrap3-editable/css/bootstrap-editable.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/x-editable/1.5.1/bootstrap3-editable/js/bootstrap-editable.js"></script>

<script type="text/javascript" language="javascript">
$(document).ready(function(){
	var dataTable = $('#sample_data').DataTable({
		"ajax":{
			url:"fetchrec.php",
			type:"POST",
		},
		createdRow:function(row, data, rowIndex)
		{
			$.each($('td', row), function(colIndex){
				if(colIndex == 1)
				{
					$(this).attr('data-name', 'name');
					$(this).attr('class', 'name');
					$(this).attr('data-type', 'text');
					$(this).attr('data-pk', data[0]);
				}
				if(colIndex == 2)
				{
					$(this).attr('data-name', 'email');
					$(this).attr('class', 'email');
					$(this).attr('data-type', 'text');
					$(this).attr('data-pk', data[0]);
				}
				if(colIndex == 3)
				{
					$(this).attr('data-name', 'phone');
					$(this).attr('class', 'phone');
					$(this).attr('data-type', 'text');
					$(this).attr('data-pk', data[0]);
				}
			});
		}
	});

	$('#sample_data').editable({
		container:'body',
		selector:'td.name',
		url:'update_rec.php',
		title:'Name',
		type:'POST',
		validate:function(value){
			if($.trim(value) == '')
			{
				return 'This field is required';
			}
		}
	});

	$('#sample_data').editable({
		container:'body',
		selector:'td.email',
		url:'update_rec.php',
		title:'Email',
		type:'POST',
		validate:function(value){
			if($.trim(value) == '')
			{
				return 'This field is required';
			}
		}
	});

	$('#sample_data').editable({
		container:'body',
		selector:'td.phone',
		url:'update_rec.php',
		title:'Phone',
		type:'POST',
		validate:function(value){
			if($.trim(value) == '')
			{
				return 'This field is required';
			}
		}
	});
});	
</script>
	</head>
	<body>
		<div class="container">
			<h3 align="center">DataTable Inline Editing using PHP Mysqli jquery ajax and X-Editable</h3>
			<br />
			<div class="panel panel-default">
				<div class="panel-heading">DataTable</div>
				<div class="panel-body">
					<div class="table-responsive">
						<table id="sample_data" class="table table-bordered table-striped">
							<thead>
								<tr>
									<th>ID</th>
									<th>Name</th>
									<th>Email</th>
									<th>Phone</th>
								</tr>
							</thead>
						</table>
					</div>
				</div>
			</div>
		</div>
		<br />
		<br />
	</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);
}
?>
fetchrec.php
//fetchrec.php
<?php
include"dbcon.php";
$result = $conn->query("SELECT * FROM employee");
$customers = $result->fetch_all(MYSQLI_ASSOC);
$data = array();
foreach($result as $row)
{
	$sub_array = array();
	$sub_array[] = $row['id'];
	$sub_array[] = $row['name'];
	$sub_array[] = $row['email'];
	$sub_array[] = $row['phone'];
	$data[] = $sub_array;
}
$output = array(
	'data'		=>	$data
);
echo json_encode($output);
?>
update_rec.php
//update_rec.php
<?php
include"dbcon.php";
$sql = "UPDATE employee SET ".$_POST["name"]." = '".$_POST["value"]."' WHERE id = '".$_POST["pk"]."'"; 
$update = $conn->query($sql); 
?>

Sunday, November 1, 2020

Flask with MongoDB how to setup and Create Read Update Delete (CRUD) methods

Flask with MongoDB how to setup and Create Read Update Delete (CRUD) methods

MongoDB is a popular database, but unlike other databases it’s classified as a NoSQL database program (MongoDB uses JSON-like documents with schema).

ModuleNotFoundError: No module named 'flask_mongoengine'

install module
(venv) C:\flaskmyproject>pip install flask-mongoengine

create file app.py
 
#app.py
import json
from flask import Flask, request, jsonify
from flask_mongoengine import MongoEngine #ModuleNotFoundError: No module named 'flask_mongoengine' = (venv) C:\flaskmyproject>pip install flask-mongoengine

app = Flask(__name__)
app.config['MONGODB_SETTINGS'] = {
    'db': 'dbtestmongo',
    'host': 'localhost',
    'port': 27017
}
db = MongoEngine()
db.init_app(app)

class User(db.Document):
    name = db.StringField()
    email = db.StringField()
    def to_json(self):
        return {"name": self.name,
                "email": self.email}

@app.route('/')
def query_records():
    name = 'tutorial101'
    user = User.objects(name=name).first()
    if not user:
        return jsonify({'error': 'data not found'})
    else:
        return jsonify(user.to_json())

@app.route('/add')
def create_record():
    user = User(name='Caite',
                email='caite@gmail.com')
    user.save()
    return jsonify(user.to_json())

@app.route('/update')
def update_record():
    name = 'tutorial101'
    user = User.objects(name=name).first()
    if not user:
        return jsonify({'error': 'data not found'})
    else:
        user.update(email='emailupdate@gmail.com')
    return jsonify(user.to_json())
	
@app.route('/delete')
def delete_record():
    name = 'tutorial101'
    user = User.objects(name=name).first()
    if not user:
        return jsonify({'error': 'data not found'})
    else:
        user.delete()
    return jsonify(user.to_json())
	
if __name__ == "__main__":
    app.run(debug=True)

Sunday, October 25, 2020

Download and install mongoDB and connect to python flask using PyMongo module

Download and install mongoDB and connect to python flask using PyMongo module

Download and install mongoDB on Windows 10 and connect to python flask using PyMongo module Source Code : In this video I am going to show How to install MongoDB on Windows 10 operating system. How to Install MongoDB Community Edition on Windows. How to Install MongoDB Compass tools How to Install python PyMongo module How to connect MongoDB to python flask pymongo and check the result MongoDB is one of the most used, open-source document database, and NoSQL database. show dbs-Print a list of all databases on the server. use {db} - Switch current database to {db} show collections-Print a list of all collections for current database. db.collection.find()-Find all documents in the collection and returns a cursor. Create database use dbtestmongo insert data db.user.insert({ "username":"tutorial101" }) show dbs show collections; db.user.find() set invironment C:\Program Files\MongoDB\Server\4.4\bin


(venv)$ pip install Flask-PyMongo
 
#app.py
from flask import Flask, jsonify
from flask_pymongo import PyMongo #(venv)$ pip install Flask-PyMongo

app = Flask(__name__)

app.config["MONGO_URI"] = "mongodb://localhost:27017/dbtestmongo"
mongo = PyMongo(app)

@app.route("/")
def index():
    online_users = mongo.db.user.find({"username": "testusername"})
    output = []
    for s in online_users:
      output.append({'User Name' : s['username']})
    return jsonify({'result' : output})
		
if __name__ == "__main__":
    app.run(debug=True)

Related Post