article

Friday, April 2, 2021

Python Flask Blog with Admin using flask_sqlalchemy, flask_login, flask_bcrypt and flask_msearch

Python Flask Blog with Admin using flask_sqlalchemy, flask_login, flask_bcrypt and flask_msearch

-- Table: user
CREATE TABLE user (
    id       INTEGER       NOT NULL,
    name     VARCHAR (80)  NOT NULL,
    username VARCHAR (80)  NOT NULL,
    email    VARCHAR (120) NOT NULL,
    password VARCHAR (200) NOT NULL,
    profile  VARCHAR (180),
    PRIMARY KEY (
        id
    ),
    UNIQUE (
        username
    ),
    UNIQUE (
        email
    )
);

INSERT INTO user (id, name, username, email, password, profile) VALUES (3, 'admin', 'admin', 'cairocoders@gmail.com', X'243262243132244A4A757A326B696734342E6835706B4A43303533382E6D315A53687369393631505278526A4D5767373337746939526372314C3761', 'profile.jpg');

-- Table: post
CREATE TABLE post (
    id       INTEGER       NOT NULL,
    title    VARCHAR (200) NOT NULL,
    slug     VARCHAR (200) NOT NULL,
    body     TEXT          NOT NULL,
    category VARCHAR (100) NOT NULL,
    image    VARCHAR (150) NOT NULL,
    user_id  INTEGER       NOT NULL,
    views    INTEGER,
    comments INTEGER,
    feature  VARCHAR       NOT NULL,
    date_pub DATETIME      NOT NULL,
    PRIMARY KEY (
        id
    ),
    UNIQUE (
        title
    ),
    UNIQUE (
        slug
    ),
    FOREIGN KEY (
        user_id
    )
    REFERENCES user (id) ON DELETE CASCADE
);

-- Table: comments
CREATE TABLE comments (
    id       INTEGER       NOT NULL,
    name     VARCHAR (200) NOT NULL,
    email    VARCHAR (200) NOT NULL,
    message  TEXT          NOT NULL,
    post_id  INTEGER       NOT NULL,
    feature  BOOLEAN       NOT NULL,
    date_pub DATETIME      NOT NULL,
    PRIMARY KEY (
        id
    ),
    FOREIGN KEY (
        post_id
    )
    REFERENCES post (id) ON DELETE CASCADE,
    CHECK (feature IN (0, 1) ) 
);

URL
http://127.0.0.1:5000/login
Username : admin
password : cairocoders

http://127.0.0.1:5000/signup
http://127.0.0.1:5000/admin
http://127.0.0.1:5000/addpost
http://127.0.0.1:5000/update/3
http://127.0.0.1:5000/comments/
http://127.0.0.1:5000/search?q=python
http://127.0.0.1:5000/news/7-essential-vs-code-extensions-for-python-developers-in-2021

pip install Flask-Bcrypt = https://pypi.org/project/Flask-Bcrypt/
pip install Flask-Login = https://pypi.org/project/Flask-Login/
pip install flask-msearch = https://pypi.org/project/flask-msearch/
pip install Flask-SQLAlchemy = https://pypi.org/project/Flask-SQLAlchemy/


templates : https://colorlib.com/wp/template/force/
app.py
 
#app.py
from flaskblog import app

if __name__ == "__main__":
    app.run(debug=True)
flaskblog/__init__.py
 
#flaskblog/__init__.py
from flask import Flask
from flask_bcrypt import Bcrypt #pip install Flask-Bcrypt https://pypi.org/project/Flask-Bcrypt/
from flask_sqlalchemy import SQLAlchemy  #pip install Flask-SQLAlchemy = https://pypi.org/project/Flask-SQLAlchemy/
from flask_login import LoginManager #pip install Flask-Login = https://pypi.org/project/Flask-Login/
from flask_msearch import Search #pip install flask-msearch = https://pypi.org/project/flask-msearch/

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///blog.db'
app.config['SECRET_KEY']='cairocoders-ednalan'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=True


db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
search = Search()
search.init_app(app)

login_manager = LoginManager(app)

login_manager.login_view = "login"
login_manager.login_message_category = "info"

from flaskblog import routes
flaskblog/routes.py
 
#flaskblog/routes.py
from flask import  render_template, redirect, url_for, request, flash,current_app,abort
from flask_login import login_user, login_required,logout_user,current_user
from flaskblog import app, bcrypt,db,search
from .forms import SignUpForm,LoginForm,PostForm
from .models import User, Post,Comments
import os 
import secrets


def save_photo(photo):
    rand_hex  = secrets.token_hex(10)
    _, file_extention = os.path.splitext(photo.filename)
    file_name = rand_hex + file_extention
    file_path = os.path.join(current_app.root_path, 'static/images', file_name)
    photo.save(file_path)
    return file_name


@app.route('/')
def index():
    posts = Post.query.order_by(Post.id.desc()).all()
    return render_template('post/index.html', posts=posts)


@app.route('/news/<string:slug>', methods=['POST','GET'])
def news(slug):
    post = Post.query.filter_by(slug=slug).first()
    comment = Comments.query.filter_by(post_id=post.id).filter_by(feature=True).all()
    post.views = post.views + 1
    db.session.commit()
    Thanks =""
    if request.method =="POST":
        post_id = post.id
        name = request.form.get('name')
        email = request.form.get('email')
        message = request.form.get('message')
        comment = Comments(name=name,email=email,message=message,post_id=post_id)
        db.session.add(comment)
        post.comments = post.comments + 1
        db.session.commit()
        flash('Your comment has been submited  submitted will be published after aproval of admin', 'success')
        return redirect(request.url)

    return render_template('post/news-details.html', post=post, comment=comment, Thanks=Thanks)


@app.route('/search')
def search():
    keyword = request.args.get('q')
    posts = Post.query.msearch(keyword,fields=['title'],limit=6)
    return render_template('post/search.html', posts=posts)
    

@app.route('/admin')
@login_required
def admin():
    posts = Post.query.order_by(Post.id.desc()).all()
    return render_template('admin/home.html',posts = posts)


@app.route('/comments/', methods=['POST','GET'])
def comments():
    comments =Comments.query.order_by(Comments.id.desc()).all()
    return render_template('admin/comment.html',comments=comments)


@app.route('/check/<int:id>', methods=['POST','GET'])
@login_required
def check(id):
    comment = Comments.query.get_or_404(id)
    if (comment.feature == True):
        comment.feature = False
        db.session.commit()
    else:
        comment.feature = True
        db.session.commit()
        return redirect(url_for('comments')) 
    return redirect(url_for('comments'))


@app.route('/addpost',methods=['POST','GET'])
@login_required
def addpost():
    form = PostForm(request.form)
    if request.method =="POST" and form.validate():
        photo = save_photo(request.files.get('photo'))
        post = Post(title=form.title.data, body=form.content.data,category=request.form.get('category'),image=photo,author=current_user)
        db.session.add(post)
        db.session.commit()
        flash('Your post has been added ','success')
        return redirect(url_for('admin'))
    return render_template('admin/addpost.html', form=form)


@app.route('/update/<int:id>',methods=['POST','GET'])
@login_required
def update(id):
    form = PostForm(request.form)
    post = Post.query.get_or_404(id)
    form.title.data = post.title 
    form.content.data = post.body
    if request.method=='POST' and form.validate():
        if request.files.get('photo'):     
            try:
                os.unlink(os.path.join(current_app.root_path, 'static/images/'+ post.image))
                post.image = save_photo(request.files.get('photo'))
            except:
                post.image = save_photo(request.files.get('photo'))
        post.title = form.title.data
        post.body = form.content.data
        post.category = request.form.get('category')
        flash('Post has been updated', 'success')
        db.session.commit()
        return redirect(url_for('admin'))
    return render_template('admin/addpost.html', form=form, post=post)


@app.route('/delete/<int:id>')
@login_required
def delete(id):
    post = Post.query.get_or_404(id)
    try:
        os.unlink(os.path.join(current_app.root_path,'static/images/'+ post.image))
        db.session.delete(post)
    except:
        db.session.delete(post)
    flash('Post has deleted ','success')
    db.session.commit()
    return redirect(url_for('admin'))

@app.route('/delcomment/<int:id>')
@login_required
def delcomment(id):
    comment = Comments.query.get_or_404(id)
    db.session.delete(comment)
    db.session.commit()
    flash('Comment has deleted ','success')
    return redirect(url_for('admin'))


@app.route('/signup', methods=['POST','GET'])
def signup():
    form = SignUpForm(request.form)
    if request.method == 'POST' and form.validate():
        hashed_password = bcrypt.generate_password_hash(form.password.data)
        user = User(name=form.name.data,username=form.username.data, email=form.email.data,password=hashed_password)
        db.session.add(user)
        db.session.commit()
        flash('Thanks for registering, you able to login now','success')
        return redirect(url_for('login'))
    return render_template('admin/signup.html', form=form)



@app.route('/login', methods=['POST','GET'])
def login(): #username : admin pass: cairocoders
    if current_user.is_authenticated:
        next = request.args.get('next')
        return redirect(next or url_for('admin'))
    form = LoginForm(request.form)
    if request.method == 'POST' and form.validate():
        user = User.query.filter_by(username=form.username.data).first()
        if not user:
            flash('This user not exists','warning')
            return redirect(url_for('login'))
        if user and bcrypt.check_password_hash(user.password, form.password.data):
            login_user(user)
            flash('Logged in successfully.','success')
            next = request.args.get('next')
            return redirect(next or url_for('admin'))
        flash('Invalid password','danger')
    return render_template('admin/login.html', form=form)


@app.route('/logout')
@login_required
def logout():
    logout_user()
    flash('you are logout','success')
    return redirect(url_for('login'))
flaskblog/models.py
 
#flaskblog/models.py
from flaskblog import db, login_manager
from datetime import datetime
from flask_login import UserMixin
from sqlalchemy import event
from slugify import slugify

@login_manager.user_loader
def load_user(user_id):
    return User.query.filter_by(id=user_id).first()

class User(db.Model,UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), nullable=False)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    password = db.Column(db.String(200),  nullable=False)
    profile = db.Column(db.String(180),  default="profile.jpg")

    def __repr__(self):
        return '<User %r>' % self.username


class Post(db.Model):
    __searchable__ = ['title', 'body']
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(200), unique=True, nullable=False)
    slug = db.Column(db.String(200), unique=True, nullable=False)
    body = db.Column(db.Text, nullable=False)
    category = db.Column(db.String(100), nullable=False)
    image = db.Column(db.String(150), nullable=False, default='no-image.jpg')
    user_id = db.Column(db.Integer, db.ForeignKey('user.id', ondelete='CASCADE'), nullable=False)
    author = db.relationship('User', backref=db.backref('posts',lazy=True, passive_deletes=True))
    views = db.Column(db.Integer,default=0)
    comments = db.Column(db.Integer,default=0)
    feature = db.Column(db.String, default=1, nullable=False)
    date_pub = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)

    def __repr__(self):
        return '<Post %r' % self.title

    @staticmethod
    def generate_slug(target, value, oldvalue, initiator):
        if value and (not target.slug or value != oldvalue):
            target.slug = slugify(value)
db.event.listen(Post.title, 'set',Post.generate_slug, retval=False)


class Comments(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(200), unique=False, nullable=False)
    email = db.Column(db.String(200), unique=False, nullable=False)
    message = db.Column(db.Text, nullable=False)
    post_id = db.Column(db.Integer, db.ForeignKey('post.id', ondelete='CASCADE'), nullable=False)
    post = db.relationship('Post', backref=db.backref('posts',lazy=True, passive_deletes=True))
    feature = db.Column(db.Boolean, default=False, nullable=False)
    date_pub = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)

    def __repr__(self):
        return '<Post %r' % self.name
flaskblog/forms.py
 
#flaskblog/forms.py
from wtforms import Form, BooleanField, StringField,FileField, PasswordField, validators, TextAreaField,ValidationError
from flask_wtf.file import FileField, FileAllowed, FileRequired

class SignUpForm(Form):
    name = StringField('Name', [validators.Length(min=2, max=25)])
    username = StringField('Username', [validators.Length(min=4, max=25)])
    email = StringField('Email Address', [validators.Length(min=6, max=35)])
    password = PasswordField('Password', [validators.DataRequired(),
        validators.EqualTo('confirm', message='Passwords must match')])
    confirm = PasswordField('Repeat Password')

class LoginForm(Form):
    username = StringField('Username', [validators.Length(min=4, max=25)])
    password = PasswordField('Password',[validators.DataRequired()])
     
class PostForm(Form):
    title = StringField('Title',[validators.DataRequired()])
    content = TextAreaField('Content', [validators.DataRequired()])
    photo = FileField()
flaskblog/templates/post/base.html
 
//flaskblog/templates/post/base.html
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="icon" href="{{ url_for('static', filename='img/favicon.png')}}" type="image/png">
    <title>Python Flask Blog with Admin using flask_sqlalchemy, flask_login, flask_bcrypt and flask_msearch</title>
    <link rel="stylesheet" href="{{url_for('static', filename='css/bootstrap.css')}}">
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css">
    <link rel="stylesheet" href="{{url_for('static', filename='css/style.css')}}">
    <link rel="stylesheet" href="{{url_for('static', filename='css/responsive.css')}}">
</head>
<body>
    <header class="header_area"> 
        <div class="logo_part">
            <div class="container">
                <div class="float-left">
                    <a class="logo" href="#"><img src="{{ url_for('static', filename='images/logo.png')}}" alt=""></a>
                </div>
            </div>
        </div>
        <div class="main_menu">
            <nav class="navbar navbar-expand-lg navbar-light">
                <div class="container">
                    <div class="container_inner">
                        <div class="collapse navbar-collapse offset" id="navbarSupportedContent">
                            <ul class="nav navbar-nav menu_nav">
                                <li class="nav-item active"><a class="nav-link" href="/">Home</a></li>
                                <li class="nav-item"><a class="nav-link" href="#">About</a></li>
                                <li class="nav-item"><a class="nav-link" href="#">Contact</a></li>
                            </ul>
                            <ul class="nav navbar-nav navbar-right ml-auto">
                                <form action="{{ url_for('search')}}" method="GET" class="input-group mr-2">
                                    <input type="text" class="form-control" name="q">
                                    <div class="input-group-append">
                                        <input type="submit" class="btn btn-outline-info" value="Search">
                                    </div>
                                </form>
                            </ul>
                        </div>
                    </div>
                </div>
            </nav>
        </div>
    </header>
    {% block content  %}

    {% endblock content %}
    <footer class="footer-area">
        <div class="container">
            <p>
                Copyright ©<script>
                    document.write(new Date().getFullYear());
                </script> All rights reserved 
            </p>
        </div>
        </div>
    </footer>
    <script src="{{url_for('static', filename='js/jquery-3.2.1.min.js')}}"></script>
    <script src="{{url_for('static', filename='js/popper.js')}}"></script>
    <script src="{{url_for('static', filename='js/bootstrap.min.js')}}"></script>
</body>
</html>
flaskblog/templates/post/index.html
#flaskblog/templates/post/index.html
    {% extends 'post/base.html' %}
    {% block content  %}
    {% include 'post/slider.html'%}
    <br>
    <section class="news_area">
    	<div class="container">
    		<div class="row">
    			<div class="col-lg-8">
    				<div class="main_title2">
    					<h2>Latest Blog</h2>
    				</div>
    				<div class="latest_news">
    					{% for post in posts %}
    					<div class="media">
    						<div class="d-flex">
    							<img class="img-fluid" src="{{url_for('static',filename='images/' + post.image)}}"
    								style="width:200px; height:200px;">
    						</div>
    						<div class="media-body">
    							<div class="choice_text">
    								<div class="date">
    									<a class="" href="#">{{post.author.name}}</a>
    									<a href="#"><i class="fa fa-calendar" aria-hidden="true"></i>March 14, 2018</a>
    									<a href="#"><i class="fa fa-comments-o" aria-hidden="true"></i> Views
    										{{post.views }} | {{post.comments}} Comennts</a>
    								</div>
    								<a href="{{url_for('news', slug=post.slug)}}">
    									<h4>{{post.title}}</h4>
    								</a>
    								<p>{{post.body |truncate(200, True) }}</p>
    							</div>
    						</div>
    					</div>
    					{% endfor %}
    				</div>
    			</div>
    		</div>
    	</div>
    </section>
    {% endblock content  %}
flaskblog/templates/post/news-details.html
#flaskblog/templates/post/news-details.html
{% extends 'post/base.html' %}
{% block content %}
        
        <section class="news_area single-post-area p_100">
        	<div class="container">
        		<div class="row">
        			<div class="col-lg-8">
       					<div class="main_blog_details">
       						<img class="img-fluid" src="{{url_for('static',filename='images/' + post.image)}}" alt="" style="width:100%; height: 400px;">
       						<h4> {{post.title}} </h4>
       						<div class="user_details">
       							<div class="float-left">
       								<a href="#">Python</a>
       								<a href="#">Flask</a>
       							</div>
       							<div class="float-right">
       								<div class="media">
       									<div class="media-body">
       										<h5>Cairocoder</h5>
       										<p>12 Dec, 2020 11:21 am</p>
       									</div>	
       								</div>
       							</div>
       						</div>
       						<p>{{post.body}}</p>
						
      						<div class="news_d_footer">
      							<a href="#"><i class="lnr lnr lnr-heart"></i>cairocoders and 4 people like this</a>
      							<a class="justify-content-center ml-auto" href="#"><i class="lnr lnr lnr-bubble"></i> {{post.views }} Views  | {{post.comments}} Comments</a>
      							<div class="news_socail ml-auto">
									<a href="#"><i class="fa fa-facebook"></i></a>
									<a href="#"><i class="fa fa-twitter"></i></a>
									<a href="#"><i class="fa fa-youtube-play"></i></a>
									<a href="#"><i class="fa fa-pinterest"></i></a>
									<a href="#"><i class="fa fa-rss"></i></a>
								</div>
      						</div>
       					</div>
                        <div class="comments-area">
							<h4>{{post.comments}} Comments</h4>
							{% for message in comment %}
                            <div class="comment-list">
                                <div class="single-comment justify-content-between d-flex">
                                    <div class="user justify-content-between d-flex">
                                        <div class="thumb">
                                            <img src="img/blog/c1.jpg" alt="">
										</div>
										
                                        <div class="desc">
                                            <h5><a href="#">{{message.name}}</a></h5>
                                            <p class="date">{{message.date_pub.strftime('%Y')}}</p>
                                            <p class="comment">
                                                {{message.message}}
                                            </p>
										</div>
										
                                    </div>
                                    <div class="reply-btn">
                                           <!-- <a href="" class="btn-reply text-uppercase">reply</a>  -->
                                    </div>
                                </div>
                            </div>	
							{% endfor %}
                    			                                             				
                        </div>
                        <div class="comment-form">
							{% include 'admin/messages.html' %}
                            <h4>Leave a Comment</h4>
                            <form method="POST">
                                <div class="form-group form-inline">
                                  <div class="form-group col-lg-6 col-md-6 name">
                                    <input type="text" name="name" class="form-control" id="name" placeholder="Enter Name" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Enter Name'">
                                  </div>
                                  <div class="form-group col-lg-6 col-md-6 email">
                                    <input type="email" name="email" class="form-control" id="email" placeholder="Enter email address" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Enter email address'">
                                  </div>										
                                </div>
                                <div class="form-group">
                                    <textarea name="message" class="form-control mb-10" rows="5" name="message" placeholder="Messege" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Messege'" required=""></textarea>
                                </div>
                                <button type="submit" class="primary-btn submit_btn">Post Comment</button>	
                            </form>
                        </div>
        			</div>
        			<div class="col-lg-4">
        				Right Side
        			</div>
        		</div>
        	</div>
        </section>	
       {% endblock content %}
flaskblog/post/search.html
//flaskblog/post/search.html
{% extends 'post/base.html' %}
{% block content %}

<section class="news_area single-post-area p_100">
	<div class="container">
		<div class="row">
			<div class="col-lg-8">
				<div class="main_blog_details">
					<div class="latest_news">
						{% for post in posts %}
						<div class="media">
							<div class="d-flex">
								<img class="img-fluid" src="{{url_for('static',filename='images/' + post.image)}}"
									style="width:200px; height:200px;">
							</div>
							<div class="media-body">
								<div class="choice_text">
									<div class="date">
										<a class="" href="#">{{post.author.name}}</a>
										<a href="#"><i class="fa fa-calendar" aria-hidden="true"></i>March 14, 2020</a>
										<a href="#"><i class="fa fa-comments-o" aria-hidden="true"></i> Views
											{{post.views }} | {{post.comments}} Comennts</a>
									</div>
									<a href="{{url_for('news', slug=post.slug)}}">
										<h4>{{post.title}}</h4>
									</a>
									<p>{{post.body |truncate(200, True) }}</p>
								</div>
							</div>
						</div>
						{% endfor %}

					</div>
				</div>
			</div>
			<div class="col-lg-4">
				Right 
			</div>
		</div>
	</div>
</section>
{% endblock content %}
flaskblog/templates/post/slider.html
//flaskblog/templates/post/slider.html
 <section class="home_banner_area">
        <div class="banner_inner d-flex align-items-center bg-light">
            <div class="container">
                <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
                    <ol class="carousel-indicators" style="position:absolute; bottom:0%;">
                        <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
                        <li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
                        <li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
                        <li data-target="#carouselExampleIndicators" data-slide-to="3"></li>
                    </ol>
                    <div class="carousel-inner">
                        
                        {% for post in posts %}
            
                        {% if loop.index == 1 %}
                        <div class="carousel-item active">
                            {% else %}
                        <div class="carousel-item">
                                {% endif %}
                              
                            <div class="background_image banner_inner" style="background-image:url('{{url_for('static', filename='images/'+ post.image)}}');">
                                <div class="banner_content text-center" style="position:absolute; right:25%; top: 50%;">
                                        <div class="date">
                                            <a href="#">Gadgets</a>
                                            <a href="#"><i class="fa fa-calendar" aria-hidden="true"></i>{{post.date_pub.strftime('%B %Y %d')}}</a>
                                            <a href="#"><i class="fa fa-comments-o" aria-hidden="true"></i>05</a>
                                        </div>
                                        <h4><a href="{{url_for('news', slug=post.slug)}}"  class="text-white" style="text-shadow:5px 5px 10px black;">{{post.title}}</a> </h4>
                                        <p style="text-shadow:5px 5px 10px black;">{{post.body| truncate(150, True)}}</p>
                                    </div>
                            </div>
                           
                        </div>
                        {% endfor %}
                    </div>
                </div>
            </div>
        </div>
    </section>  
flaskblog/templates/admin/login.html
//flaskblog/templates/admin/login.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <link rel="icon" href="static/web.jpg">
    <title> Login</title>
  </head>
  <body>
    <h1 class="text-center">  Login now </h1>
    {% from "admin/_formhelpers.html" import render_field %}
 <div class="container">
    <div class="row">
        <div class="col-md-3"></div>
        <div class="col-md-6">
          {% include 'admin/messages.html' %}
                <form method="post">
                        <div>
                          {{ render_field(form.username, class="form-control") }} 
                          {{ render_field(form.password, class="form-control") }}
                        </div>
                        <p><input type=submit value="Login" class="btn btn-info">
                      </form>
        </div>
        <div class="col-md-3"></div>
    </div>
 </div>
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
  </body>
</html>
flaskblog/templates/admin/signup.html
//flaskblog/templates/admin/signup.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <link rel="icon" href="static/web.jpg">
    <title> Sign Up</title>
  </head>
  <body>
    <h1 class="text-center"> Sign up now </h1>
    {% from "admin/_formhelpers.html" import render_field %}
 <div class="container">
    <div class="row">
        <div class="col-md-3"></div>
        <div class="col-md-6">
          {% include 'admin/messages.html' %}
                <form method="post">
                        <div>
                          {{ render_field(form.name, class="form-control")}}
                          {{ render_field(form.username, class="form-control") }}
                          {{ render_field(form.email, class="form-control") }}
                          {{ render_field(form.password, class="form-control") }}
                          {{ render_field(form.confirm, class="form-control") }}
                        </div>
                        <p><input type=submit value="Register" class="btn btn-info">
                      </form>
        </div>
        <div class="col-md-3"></div>
    </div>
 </div>
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
  </body>
</html>
flaskblog/templates/admin/home.html
//flaskblog/templates/admin/home.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <title> Dashboard </title>
  </head>
  <body>
    <h2 class="text-center">User  Dashboard </h2>
    {% include 'admin/messages.html' %}
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
      <a class="navbar-brand" href="{{url_for('admin')}}">Navbar</a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <ul class="navbar-nav mr-auto">
          <li class="nav-item active">
            <a class="nav-link" href="{{url_for('admin')}}">Home <span class="sr-only">(current)</span></a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="{{url_for('addpost')}}">Add post</a>
          </li>
          <li class="nav-item">
              <a class="nav-link" href="{{url_for('comments')}}">Comments</a>
            </li>
        </ul>
        <ul class="navbar-nav">
          <li class="nav-item">
            <a class="nav-link" href="{{ url_for('logout')}}"aria-disabled="true">Logout</a>
          </li>
        </ul>
      </div>
    </nav>

    <table class="table table-striped table-bordered table-sm">
      <thead class="bg-dark text-white">
        <th>Sr</th>
        <th>Title</th>
        <th>Category</th>
        <th>Author</th>
        <th>Date</th>
        <th>Image</th>
        <th>Edit</th>
        <th>Delete</th>
      </thead>
       <tbody>
         {% for post in posts %}
         <tr>
           <td>{{loop.index}}</td>
           <td>{{post.title}}</td>
           <td>{{post.category}}</td>
           <td>{{post.author.name}}</td>
           <td>{{post.date_pub.strftime('%Y %B %d')}}</td>
           <td> <img src="{{url_for('static', filename='images/' + post.image)}}" alt="{{post.category}}" width="40"></td>
           <td> <a href="update/{{ post.id}}" class="btn btn-sm btn-info">Edit</a> </td>
    
           <td><button type="button" class="btn btn-danger btn-sm" data-toggle="modal" data-target="#del{{post.id}}">
              delete
            </button></td>
         </tr>
  <!-- The Modal -->
  <div class="modal" id="del{{post.id}}">
    <div class="modal-dialog">
      <div class="modal-content">
        <!-- Modal Header -->
        <div class="modal-header">
          <h4 class="modal-title text-danger"> Are you do you want delete this post </h4>
          <button type="button" class="close" data-dismiss="modal">×</button>
        </div>
        <div class="modal-body">
         {{post.title}}
        </div>
        <div class="modal-footer">
         <div class="mr-auto"> <a href="delete/{{ post.id}}" class="btn btn-danger btn-sm"> Delete </a></div>
          <button type="button" class="btn btn-primary btn-sm" data-dismiss="modal">Cancel</button>
        </div>
      </div>
    </div>
  </div>
         {% endfor %}
       </tbody>
    </table>
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
  </body>
</html>
flaskblog/templates/admin/comment.html
//flaskblog/templates/admin/comment.html
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <script src="https://code.jquery.com/jquery-3.4.0.js">
    </script>
    <title> Dashboard-Comments </title>
</head>
<body>
    <h2 class="text-center">Dashboard-Comments </h2>
    {% include 'admin/messages.html' %}
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
        <a class="navbar-brand" href="{{url_for('admin')}}">Navbar</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarSupportedContent">
            <ul class="navbar-nav mr-auto">
                <li class="nav-item active">
                    <a class="nav-link" href="{{url_for('admin')}}">Home <span class="sr-only">(current)</span></a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="{{url_for('addpost')}}">Add post</a>
                </li>
            </ul>
            <ul class="navbar-nav">
                <li class="nav-item">
                    <a class="nav-link" href="{{ url_for('logout')}}" aria-disabled="true">Logout</a>
                </li>
            </ul>
        </div>
    </nav>
    <table class="table table-striped table-bordered table-sm">
        <thead class="bg-dark text-white">
            <th>Sr</th>
            <th>Name</th>
            <th>Comments</th>
            <th>Post ID</th>
            <th>Date</th>
            <th>Status</th>
            <td>Delete</td>
        </thead>
        <tbody>
            {% for comment in comments %}
            <tr>
                <td>{{loop.index}}</td>
                <td>{{comment.name}}</td>
                <td>{{comment.message | truncate(100, True)}}</td>
                <td>{{comment.post.id}}</td>
                <!-- <td>{{comment.feature}}</td> -->
                <td>{{comment.date_pub.strftime('%Y %B %d')}}
                </td>
                {% if comment.feature == False %}
                <td>
                    <a href="{{ url_for('check', id=comment.id) }}" class="text-center text-danger"> Pandding </a>
                </td>
                {% else %}
                <td>
                    <a href="{{ url_for('delcomment', id=comment.id) }}" class="text-success"> Aproved </a>
                </td>
                {% endif %}
                <td>
                    <a href="{{ url_for('check', id=comment.id) }}" class="btn btn-sm btn-danger"> Delete </a>
                </td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js">
    </script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js">
    </script>
</body>
</html>
flaskblog/templates/admin/messages.html
//flaskblog/templates/admin/messages.html
{% with messages = get_flashed_messages(with_categories=true) %}
  {% if messages %}
    <div class=flashes>
    {% for category, message in messages %}
      <div class=" alert alert-{{ category }}">{{ message }}</div>
    {% endfor %}
    </div>
  {% endif %}
{% endwith %}
flaskblog/templates/admin/_formhelpers.html
//flaskblog/templates/admin/_formhelpers.html
{% macro render_field(field) %}
  <dt>{{ field.label }}
  <dd>{{ field(**kwargs)|safe }}
  {% if field.errors %}
    <ul class=errors>
    {% for error in field.errors %}
      <li class="text-danger">{{ error }}</li>
    {% endfor %}
    </ul>
  {% endif %}
  </dd>
{% endmacro %}

Tuesday, March 30, 2021

5 Star Rating Using PHP Mysql and jQuery AJAX

5 Star Rating Using PHP Mysql and jQuery AJAX

In this tutorial, I am using jquery bar raging plugin to display the star rating 

http://github.com/antennaio/jquery-bar-rating

--
-- Table structure for table `post_rating`
--

CREATE TABLE `post_rating` (
  `id` int(11) NOT NULL,
  `userid` int(11) NOT NULL,
  `postid` int(11) NOT NULL,
  `rating` int(2) NOT NULL,
  `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `post_rating`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `post_rating`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;


--
-- Table structure for table `posts`
--

CREATE TABLE `posts` (
  `id` int(11) NOT NULL,
  `title` varchar(100) NOT NULL,
  `content` text NOT NULL,
  `link` varchar(255) NOT NULL,
  `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `posts`
--

INSERT INTO `posts` (`id`, `title`, `content`, `link`, `timestamp`) VALUES
(1, 'Yes, except the Dave Matthews Band doesn\'t rock.', 'The alien mothership is in orbit here. If we can hit that bullseye, the rest of the dominoes will fall like a house of cards. Checkmate. If rubbin\' frozen dirt in your crotch is wrong, hey I don\'t wanna be right.', 'link-1', '2021-03-21 05:41:54'),
(2, 'Saving the world with meals on wheels.', 'You know how I sometimes have really brilliant ideas? Heh-haa! Super squeaky bum time! I\'m the Doctor. Well, they call me the Doctor. I don\'t know why. I call me the Doctor too. I still don\'t know why.', 'link-2', '2021-03-21 05:42:02'),
(3, 'Tell him time is of the essence.', 'This man is a knight in shining armor. Watching ice melt. This is fun. Tell him time is of the essence. This man is a knight in shining armor. You look perfect. He taught me a code. To survive.', 'link-3', '2021-03-21 05:42:08'),
(4, 'What is AngularJS', 'AngularJS is a JavaScript MVC framework  developed by Google that lets you build well structured, easily testable,  declarative and maintainable front-end applications which provides solutions to  standard infrastructure concerns.', 'link-5', '2021-03-20 16:00:00'),
(5, 'What is MongoDB', 'It is a quick tutorial on MongoDB and how you can install it on your Windows OS. We will also learn some basic commands in MongoDB for example, creating and dropping a Database, Creation of a collection and some more operations related to the collection.', 'link-6', '2021-03-21 16:00:00'),
(6, 'Python Flask Load content Dynamically in Bootstrap Modal with Jquery AJAX and Mysqldb', 'Python Flask Load content Dynamically in Bootstrap Modal with Jquery AJAX and Mysqldb', 'link-6', '2021-03-20 16:00:00'),
(7, 'AutoComplete Textbox with Image using jQuery Ajax PHP Mysql and JqueryUI', 'AutoComplete Textbox with Image using jQuery Ajax PHP Mysql and JqueryUI', 'link-7', '2021-03-14 16:00:00'),
(8, 'PHP Mysql Registration Form Validation using jqBootstrapValidation with Jquery Ajax', 'PHP Mysql Registration Form Validation using jqBootstrapValidation with Jquery Ajax', 'link-8', '2021-03-20 16:00:00'),
(9, 'Python Flask Registration Form Validation using jqBootstrapValidation with Jquery Ajax and Mysql', 'Python Flask Registration Form Validation using jqBootstrapValidation with Jquery Ajax and Mysql', 'link-9', '2021-03-19 16:00:00'),
(10, 'Displaying Popups data on mouse hover using Jquery Ajax and PHP Mysql database', 'Displaying Popups data on mouse hover using Jquery Ajax and PHP Mysql database', 'link-10', '2021-03-15 16:00:00'),
(11, 'Displaying Popups data on mouse hover using Jquery Ajax and Python Flask Mysql database', 'Displaying Popups data on mouse hover using Jquery Ajax and Python Flask Mysql database', 'link-11', '2021-03-14 16:00:00');

--
-- Indexes for dumped tables
--

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

--
-- AUTO_INCREMENT for dumped tables
--

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

index.php
//index.php
<html>
<head>
<title>5 Star Rating Using PHP Mysql and jQuery AJAX</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css">
<link href='jquery-bar-rating-master/dist/themes/fontawesome-stars.css' rel='stylesheet' type='text/css'>
<script src="jquery-3.0.0.js" type="text/javascript"></script>
<script src="jquery-bar-rating-master/dist/jquery.barrating.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
            $('.rating').barrating({
                theme: 'fontawesome-stars',
                onSelect: function(value, text, event) {
                    var el = this;
                    var el_id = el.$elem.data('id');
                    if (typeof(event) !== 'undefined') {
                        var split_id = el_id.split("_");
                        var postid = split_id[1];  
                        $.ajax({
                            url: 'rating_ajax.php',
                            type: 'post',
                            data: {postid:postid,rating:value},
                            dataType: 'json',
                            success: function(data){
                                var average = data['averageRating'];
                                $('#avgrating_'+postid).text(average);
                            }
                        });
                    }
                }
            });
        });
</script>
</head>
<body>
<p><h1 align="center">5 Star Rating Using PHP Mysql and jQuery AJAX</h1></p>
<div class="content">
<?php
include "dbcon.php";
$userid = 4;
$query = "SELECT * FROM posts";
$result = mysqli_query($conn,$query);
while($row = mysqli_fetch_array($result)){
    $postid = $row['id'];
    $title = $row['title'];
    $conntent = $row['content'];
    $link = $row['link'];

    $query = "SELECT * FROM post_rating WHERE postid=".$postid." and userid=".$userid;
    $userresult = mysqli_query($conn,$query) or die(mysqli_error());
    $fetchRating = mysqli_fetch_array($userresult);
    $rating = $fetchRating['rating'];

    $query = "SELECT ROUND(AVG(rating),1) as averageRating FROM post_rating WHERE postid=".$postid;
    $avgresult = mysqli_query($conn,$query) or die(mysqli_error());
    $fetchAverage = mysqli_fetch_array($avgresult);
    $averageRating = $fetchAverage['averageRating'];

    if($averageRating <= 0){
        $averageRating = "No rating yet.";
    }
?>
    <div class="post">
        <h1><a href='<?php echo $link; ?>' class='link' target='_blank'><?php echo $title; ?></a></h1>
        <div class="post-text">
            <?php echo $conntent; ?>
        </div>
        <div class="post-action">
            <select class='rating' id='rating_<?php echo $postid; ?>' data-id='rating_<?php echo $postid; ?>'>
                <option value="1" >1</option>
                <option value="2" >2</option>
                <option value="3" >3</option>
                <option value="4" >4</option>
                <option value="5" >5</option>
            </select>
            <div style='clear: both;'></div>
                Average Rating : <span id='avgrating_<?php echo $postid; ?>'><?php echo $averageRating; ?></span>
            <script type='text/javascript'>
                $(document).ready(function(){
                    $('#rating_<?php echo $postid; ?>').barrating('set',<?php echo $rating; ?>);
                });     
            </script>
        </div>
    </div>
<?php
    }
?>
</div>
<style>
.content{
    border: 0px solid black;
    border-radius: 3px;
    padding: 5px;
    margin: 0 auto;
    width: 50%;
}
.post{
    border-bottom: 1px solid black;
    padding: 10px;
    margin-top: 10px;
    margin-bottom: 10px;
}
.post:last-child{
    border: 0;
}
.post h1{
    font-weight: normal;
    font-size: 30px;
}
.post a.link{
    text-decoration: none;
    color: black;
}
.post-text{
    letter-spacing: 1px;
    font-size: 15px;
    font-family: serif;
    color: gray;
    text-align: justify;
}
.post-action{
    margin-top: 15px;
    margin-bottom: 15px;
}

.like,.unlike{
    border: 0;
    background: none;
    letter-spacing: 1px;
    color: lightseagreen;
}
.like,.unlike:hover{
    cursor: pointer;
}
</style>
</body>
</html>
rating_ajax.php
//rating_ajax.php
<?php
include "dbcon.php";
$userid = 4;
$postid = $_POST['postid'];
$rating = $_POST['rating'];

$query = "SELECT COUNT(*) AS cntpost FROM post_rating WHERE postid=".$postid." and userid=".$userid;

$result = mysqli_query($conn,$query);
$fetchdata = mysqli_fetch_array($result);
$count = $fetchdata['cntpost'];

if($count == 0){
    $insertquery = "INSERT INTO post_rating(userid,postid,rating) values(".$userid.",".$postid.",".$rating.")";
    mysqli_query($conn,$insertquery);
}else {
    $updatequery = "UPDATE post_rating SET rating=" . $rating . " where userid=" . $userid . " and postid=" . $postid;
    mysqli_query($conn,$updatequery);
}

$query = "SELECT ROUND(AVG(rating),1) as averageRating FROM post_rating WHERE postid=".$postid;
$result = mysqli_query($conn,$query) or die(mysqli_error());
$fetchAverage = mysqli_fetch_array($result);
$averageRating = $fetchAverage['averageRating'];
$return_arr = array("averageRating"=>$averageRating);

echo json_encode($return_arr);

Tuesday, March 23, 2021

Load more data using jQuery AJAX and PHP Mysql

Load more data using jQuery AJAX and PHP Mysql


--
-- Table structure for table `posts`
--

CREATE TABLE `posts` (
  `id` int(11) NOT NULL,
  `title` varchar(100) NOT NULL,
  `content` text NOT NULL,
  `link` varchar(255) NOT NULL,
  `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `posts`
--

INSERT INTO `posts` (`id`, `title`, `content`, `link`, `timestamp`) VALUES
(1, 'Yes, except the Dave Matthews Band doesn\'t rock.', 'The alien mothership is in orbit here. If we can hit that bullseye, the rest of the dominoes will fall like a house of cards. Checkmate. If rubbin\' frozen dirt in your crotch is wrong, hey I don\'t wanna be right.', 'link-1', '2021-03-21 05:41:54'),
(2, 'Saving the world with meals on wheels.', 'You know how I sometimes have really brilliant ideas? Heh-haa! Super squeaky bum time! I\'m the Doctor. Well, they call me the Doctor. I don\'t know why. I call me the Doctor too. I still don\'t know why.', 'link-2', '2021-03-21 05:42:02'),
(3, 'Tell him time is of the essence.', 'This man is a knight in shining armor. Watching ice melt. This is fun. Tell him time is of the essence. This man is a knight in shining armor. You look perfect. He taught me a code. To survive.', 'link-3', '2021-03-21 05:42:08'),
(4, 'What is AngularJS', 'AngularJS is a JavaScript MVC framework  developed by Google that lets you build well structured, easily testable,  declarative and maintainable front-end applications which provides solutions to  standard infrastructure concerns.', 'link-5', '2021-03-20 16:00:00'),
(5, 'What is MongoDB', 'It is a quick tutorial on MongoDB and how you can install it on your Windows OS. We will also learn some basic commands in MongoDB for example, creating and dropping a Database, Creation of a collection and some more operations related to the collection.', 'link-6', '2021-03-21 16:00:00'),
(6, 'Python Flask Load content Dynamically in Bootstrap Modal with Jquery AJAX and Mysqldb', 'Python Flask Load content Dynamically in Bootstrap Modal with Jquery AJAX and Mysqldb', 'link-6', '2021-03-20 16:00:00'),
(7, 'AutoComplete Textbox with Image using jQuery Ajax PHP Mysql and JqueryUI', 'AutoComplete Textbox with Image using jQuery Ajax PHP Mysql and JqueryUI', 'link-7', '2021-03-14 16:00:00'),
(8, 'PHP Mysql Registration Form Validation using jqBootstrapValidation with Jquery Ajax', 'PHP Mysql Registration Form Validation using jqBootstrapValidation with Jquery Ajax', 'link-8', '2021-03-20 16:00:00'),
(9, 'Python Flask Registration Form Validation using jqBootstrapValidation with Jquery Ajax and Mysql', 'Python Flask Registration Form Validation using jqBootstrapValidation with Jquery Ajax and Mysql', 'link-9', '2021-03-19 16:00:00'),
(10, 'Displaying Popups data on mouse hover using Jquery Ajax and PHP Mysql database', 'Displaying Popups data on mouse hover using Jquery Ajax and PHP Mysql database', 'link-10', '2021-03-15 16:00:00'),
(11, 'Displaying Popups data on mouse hover using Jquery Ajax and Python Flask Mysql database', 'Displaying Popups data on mouse hover using Jquery Ajax and Python Flask Mysql database', 'link-11', '2021-03-14 16:00:00');

--
-- Indexes for dumped tables
--

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

--
-- AUTO_INCREMENT for dumped tables
--

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



index.php
//index.php
<!doctype html>
<html>
<head>
<title>Load more data using jQuery,AJAX, and PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<style>
.container{
    width: 55%;
    margin: 0 auto;
    border: 0px solid black;
    padding: 10px 0px;
}
.post{
    width: 97%;
    min-height: 200px;
    padding: 5px;
    border: 1px solid gray;
    margin-bottom: 15px;
}
.post h1{
    letter-spacing: 1px;
    font-weight: normal;
    font-family: sans-serif;
}
.post p{
    letter-spacing: 1px;
    text-overflow: ellipsis;
    line-height: 25px;
}
.load-more{
    width: 99%;
    background: #15a9ce;
    text-align: center;
    color: white;
    padding: 10px 0px;
    font-family: sans-serif;
}
.load-more:hover{
    cursor: pointer;
}
.more{
    color: blue;
    text-decoration: none;
    letter-spacing: 1px;
    font-size: 16px;
}
</style>
</head>
<body>
<div class="container">
<h2 align="center">Load more data using jQuery AJAX and PHP Mysql</a></h2>
   <br />
    <?php
	include "config.php";
            $rowperpage = 3;
            // counting total number of posts
            $allcount_query = "SELECT count(*) as allcount FROM posts";
            $allcount_result = mysqli_query($con,$allcount_query);
            $allcount_fetch = mysqli_fetch_array($allcount_result);
            $allcount = $allcount_fetch['allcount'];
            // select first 3 posts
            $query = "select * from posts order by id asc limit 0,$rowperpage ";
            $result = mysqli_query($con,$query);
            while($row = mysqli_fetch_array($result)){
                $id = $row['id'];
                $title = $row['title'];
                $content = $row['content'];
                $shortcontent = substr($content, 0, 160)."...";
                $link = $row['link'];
            ?>
                <div class="post" id="post_<?php echo $id; ?>">
                    <h1><?php echo $title; ?></h1>
                    <p><?php echo $shortcontent; ?></p>
                    <a href="<?php echo $link; ?>" class="more" target="_blank">More</a>
                </div>
            <?php
            }
            ?>
            <h1 class="load-more">Load More</h1>
            <input type="hidden" id="row" value="0">
            <input type="hidden" id="all" value="<?php echo $allcount; ?>">
</div>
<script>
$(document).ready(function(){
    $('.load-more').click(function(){
        var row = Number($('#row').val());
        var allcount = Number($('#all').val());
        row = row + 3;
        if(row <= allcount){
            $("#row").val(row);
            $.ajax({
                url: 'getData.php',
                type: 'post',
                data: {row:row},
                beforeSend:function(){
                    $(".load-more").text("Loading...");
                },
                success: function(response){
                    setTimeout(function() {
                        $(".post:last").after(response).show().fadeIn("slow");
                        var rowno = row + 3;
                        if(rowno > allcount){
                            $('.load-more').text("Hide");
                            $('.load-more').css("background","darkorchid");
                        }else{
                            $(".load-more").text("Load more");
                        }
                    }, 2000);
                }
            });
        }else{
            $('.load-more').text("Loading...");
            setTimeout(function() {
                $('.post:nth-child(3)').nextAll('.post').remove().fadeIn("slow");
                $("#row").val(0);
                $('.load-more').text("Load more");
                $('.load-more').css("background","#15a9ce");
            }, 2000);
        }
    });
});
</script>		
</body>
</html>
config.php
//config.php
<?php
$host = "localhost"; 
$user = "root";
$password = ""; 
$dbname = "testingdb"; 

$con = mysqli_connect($host, $user, $password,$dbname);
if (!$con) {
 die("Connection failed: " . mysqli_connect_error());
}
getData.php
//getData.php
<?php
include 'config.php';
$row = $_POST['row'];
$rowperpage = 3;
$query = 'SELECT * FROM posts limit '.$row.','.$rowperpage;
$result = mysqli_query($con,$query);
$html = '';
while($row = mysqli_fetch_array($result)){
    $id = $row['id'];
    $title = $row['title'];
    $content = $row['content'];
    $shortcontent = substr($content, 0, 160)."...";
    $link = $row['link'];

    $html .= '<div id="post_'.$id.'" class="post">';
    $html .= '<h1>'.$title.'</h1>';
    $html .= '<p>'.$shortcontent.'</p>';
    $html .= '<a href="'.$link.'" class="more" target="_blank">More</a>';
    $html .= '</div>';
}
echo $html;

Saturday, March 20, 2021

Python Flask Load content Dynamically in Bootstrap Modal with Jquery AJAX and Mysqldb

Python Flask Load content Dynamically in Bootstrap Modal with Jquery AJAX and Mysqldb

--
-- 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,
  `photo` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

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

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

--
-- 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=19;
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 ASC")
    employee = cur.fetchall()  
    return render_template('index.html', employee = employee)

@app.route("/ajaxfile",methods=["POST","GET"])
def ajaxfile():
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    if request.method == 'POST':
        userid = request.form['userid']
        print(userid)
        cur.execute("SELECT * FROM employee WHERE id = %s", [userid])
        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
<!DOCTYPE html>
<html>
<head>
<title>Python Flask Load content Dynamically in Bootstrap Modal with Jquery AJAX and Mysqldb</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 />
   <h3 align="center">Python Flask Load content Dynamically in Bootstrap Modal with Jquery AJAX and Mysqldb</h3>
   <div class="row">
    <div class="col-md-12">
        <div class="panel-body">
			<div class="table-responsive">
                <table class="table table-bordered">
                    <thead>
                        <tr>
                            <th width="60">Photo</th>
                            <th>Name</th>
                            <th>Position</th>
                            <th>Office</th>
                            <th>Age</th>
                            <th>Salary</th>
                            <th>View</th>
                        </tr>
                        </thead> 
                        {% for row in employee %}
                            <tr>
                                <td><img src="/static/images/{{row.photo}}" height="50" width="50"/></td>
                                <td>{{row.oname}}</td>
                                <td>{{row.position}}</td>
                                <td>{{row.office}}</td>
                                <td>{{row.age}}</td>
                                <td>{{row.salary}}</td>
                                <td><button data-id='{{row.id}}' class="userinfo btn btn-success">Info</button></td>
                            </tr>
                        {% endfor %}
                </table>
            </div>
		</div>	
	</div>	
	</div>
</div>	
            <script type='text/javascript'>
            $(document).ready(function(){
                $('.userinfo').click(function(){
                    var userid = $(this).data('id');
                    $.ajax({
                        url: '/ajaxfile',
                        type: 'post',
                        data: {userid: userid},
                        success: function(data){ 
                            $('.modal-body').html(data); 
                            $('.modal-body').append(data.htmlresponse);
                            $('#empModal').modal('show'); 
                        }
                    });
                });
            });
            </script>
        </div>
        <div class="modal fade" id="empModal" role="dialog">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h4 class="modal-title">User Info</h4>
                          <button type="button" class="close" data-dismiss="modal">×</button>
                        </div>
                        <div class="modal-body">
                        </div>
                        <div class="modal-footer">
                          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                        </div>
                    </div>
                </div>
        </div>
    </body>
</html>
templates/response.html
//templates/response.html
{% for row in employeelist %} 
<table border='0' width='100%'>
    <tr>
        <td width="300"><img src="/static/images/{{row.photo}}">
        <td style="padding:20px;">
        <p>Name : {{row.name}}</p>
        <p>Position : {{row.position}}</p>
        <p>Office : {{row.office}}</p>
        <p>Age : {{row.age}}</p>
        <p>Salary : {{row.salary}}</p>
        </td>
    </tr>
</table>
{% endfor %}

Friday, March 19, 2021

Load content Dynamically in Bootstrap Modal with Jquery AJAX PHP and Mysql

Load content Dynamically in Bootstrap Modal with Jquery AJAX PHP and Mysql


--
-- 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,
  `photo` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

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

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

--
-- 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=19;





Index.php
<!DOCTYPE html>
<html>
<head>
<title>Load content Dynamically in Bootstrap Modal with Jquery AJAX PHP and Mysql</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 />
   <h3 align="center">Load content Dynamically in Bootstrap Modal with Jquery AJAX PHP and Mysql</h3>
   <div class="row">
    <div class="col-md-12">
        <div class="panel-body">
            <?php 
				include "dbcon.php";
                $query = "select * from employee";
                $result = mysqli_query($conn,$query);
			?>
			<div class="table-responsive">
                <table class="table table-bordered">
                    <thead>
                        <tr>
                            <th width="60">Photo</th>
                            <th>Name</th>
                            <th>Position</th>
                            <th>Office</th>
                            <th>Age</th>
                            <th>Salary</th>
                            <th>View</th>
                        </tr>
                        </thead> 
                        <?php while($row = mysqli_fetch_array($result)){ ?>
                            <tr>
                                <td><img src="images/<?php echo $row['photo']; ?>" height="50" width="50"/></td>
                                <td><?php echo $row['name']; ?></td>
                                <td><?php echo $row['position']; ?></td>
                                <td><?php echo $row['office']; ?></td>
                                <td><?php echo $row['age']; ?></td>
                                <td><?php echo $row['salary']; ?></td>
                                <td><button data-id='<?php echo $row['id']; ?>' class="userinfo btn btn-success">Info</button></td>
                            </tr>
                        <?php } ?>
                </table>
            </div>
		</div>	
	</div>	
	</div>
</div>	
            <script type='text/javascript'>
            $(document).ready(function(){
                $('.userinfo').click(function(){
                    var userid = $(this).data('id');
                    $.ajax({
                        url: 'ajaxfile.php',
                        type: 'post',
                        data: {userid: userid},
                        success: function(response){ 
                            $('.modal-body').html(response); 
                            $('#empModal').modal('show'); 
                        }
                    });
                });
            });
            </script>
        </div>
        <div class="modal fade" id="empModal" role="dialog">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h4 class="modal-title">User Info</h4>
                          <button type="button" class="close" data-dismiss="modal">×</button>
                        </div>
                        <div class="modal-body">
                        </div>
                        <div class="modal-footer">
                          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                        </div>
                    </div>
                </div>
        </div>
    </body>
</html>
ajaxfile.php
<?php
include "dbcon.php";

$userid = $_POST['userid'];

$sql = "select * from employee where id=".$userid;
$result = mysqli_query($conn,$sql);
while( $row = mysqli_fetch_array($result) ){
?>
<table border='0' width='100%'>
<tr>
	<td width="300"><img src="images/<?php echo $row['photo']; ?>">
	<td style="padding:20px;">
	<p>Name : <?php echo $row['name']; ?></p>
	<p>Position : <?php echo $row['position']; ?></p>
	<p>Office : <?php echo $row['office']; ?></p>
	<p>Age : <?php echo $row['age']; ?></p>
	<p>Salary : <?php echo $row['salary']; ?></p>
	</td>
</tr>
</table>

<?php } ?>
dbcon.php
//dbcon.php
<?php
$conn = new mysqli('localhost','root','','testingdb');
if ($conn->connect_error) {
    die('Error : ('. $conn->connect_errno .') '. $conn->connect_error);
}
?>

Wednesday, February 24, 2021

AutoComplete Textbox with Image using jQuery Ajax PHP Mysql and JqueryUI

AutoComplete Textbox with Image using jQuery Ajax PHP Mysql and JqueryUI

https://jqueryui.com/

https://jqueryui.com/autocomplete/

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

--
-- 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,
  `photo` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

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

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

--
-- 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=19;
index.php
//index.php
<!DOCTYPE html>
<html>
  <head>
    <title>AutoComplete Textbox with Image using jQuery Ajax PHP Mysql and JqueryUI</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

    <style type="text/css">
      .ui-autocomplete-row
      {
        padding:8px;
        background-color: #f4f4f4;
        border-bottom:1px solid #ccc;
        font-weight:bold;
      }
      .ui-autocomplete-row:hover
      {
        background-color: #ddd;
      }
    </style>
  </head>
  <body>
    <div class="container" style="padding:120px;">
      <h3 align="center">AutoComplete Textbox with Image using jQuery Ajax PHP Mysql and JqueryUI</h3>
      <div class="row">
        <div class="col-md-12">
          <input type="text" id="search_data" placeholder="Enter Employee Name..." autocomplete="off" class="form-control input-lg" />
        </div>
      </div>
    </div>
<script>
$(document).ready(function(){
    $('#search_data').autocomplete({
      source: "fetch_data.php",
      minLength: 1,
      select: function(event, ui)
      {
        $('#search_data').val(ui.item.value);
      }
    }).data('ui-autocomplete')._renderItem = function(ul, item){
      return $("<li class='ui-autocomplete-row'></li>")
        .data("item.autocomplete", item)
        .append(item.label)
        .appendTo(ul);
    };
});
</script>
</body>
</html>
fetch_data.php
//fetch_data.php
<?php
include('dbcon.php');
if(isset($_GET["term"]))
{
	$result = $conn->query("SELECT * FROM employee WHERE name LIKE '%".$_GET["term"]."%' ORDER BY name ASC");
    $total_row = mysqli_num_rows($result); 
	$output = array();
	if($total_row > 0){
	  foreach($result as $row)
	  {
	   $temp_array = array();
	   $temp_array['value'] = $row['name'];
	   $temp_array['label'] = '<img src="images/'.$row['photo'].'" width="70" />   '.$row['name'].'';
	   $output[] = $temp_array;
	  }
	}else{
	  $output['value'] = '';
	  $output['label'] = 'No Record Found';
	}
 echo json_encode($output);
}
?>
dbcon.php
//dbcon.php
<?php
$conn = new mysqli('localhost','root','','testingdb');
if ($conn->connect_error) {
    die('Error : ('. $conn->connect_errno .') '. $conn->connect_error);
}
?>

PHP Mysql Registration Form Validation using jqBootstrapValidation with Jquery Ajax

PHP Mysql Registration Form Validation using jqBootstrapValidation with Jquery Ajax

jqBootstrapValidation https://reactiveraven.github.io/jqBootstrapValidation/

A JQuery validation plugin for bootstrap forms.

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

CREATE TABLE `tbl_user` (
  `id` int(11) NOT NULL,
  `username` varchar(150) NOT NULL,
  `email` varchar(150) NOT NULL,
  `password` varchar(150) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

--
-- Dumping data for table `tbl_user`
--

INSERT INTO `tbl_user` (`id`, `username`, `email`, `password`) VALUES
(1, 'cairocoders', 'cairodoers@gmail.com', 'tutorial101');

--
-- Indexes for dumped tables
--

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

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_user`
--
ALTER TABLE `tbl_user`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
index.php
//index.php
<!DOCTYPE html>
<html>
<head>
<title>PHP Mysql Registration Form Validation using jqBootstrapValidation with 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/jqBootstrapValidation/1.3.6/jqBootstrapValidation.js"></script>
<style>
.controls p{
    color:#a94442;
}
</style>
</head>
<body>
<div class="container">
<br />
<h3 align="center">PHP Mysql Registration Form Validation using jqBootstrapValidation with Jquery Ajax</h3>
<br />
<form class="form-horizontal" method="POST" id="simple_form" novalidate="novalidate">
  <fieldset>
    <div id="legend">
      <legend class="">Register</legend>
    </div>
    <div class="control-group">
      <label class="control-label"  for="username">Username</label>
      <div class="controls">
        <input type="text" id="username" name="username" class="form-control form-control-lg" placeholder="Name" required="required" data-validation-required-message="Please enter your Username">
        <p class="text-danger help-block"></p>
      </div>
    </div>
 
    <div class="control-group">
      <label class="control-label" for="email">E-mail</label>
      <div class="controls">
        <input type="email" id="email" name="email" class="form-control form-control-lg" placeholder="Email" required="required" data-validation-required-message="Please provide your E-mail">
        <p class="text-danger help-block"></p>
      </div>
    </div>
 
    <div class="control-group">
      <label class="control-label" for="password">Password</label>
      <div class="controls">
        <input type="password" id="password" name="password" class="form-control form-control-lg" placeholder="Password" required="required" data-validation-required-message="Please provide your password">
        <p class="text-danger help-block"></p>
      </div>
    </div>
 
    <div class="control-group">
      <label class="control-label"  for="password_confirm">Password (Confirm)</label>
      <div class="controls">
        <input type="password" id="password_confirm" class="form-control form-control-lg" name="password_confirm" placeholder="Password (Confirm)" required="required" data-validation-required-message="Please confirm password">
        <p class="text-danger help-block"></p>
      </div>
    </div>
 
    <div class="control-group">
		<div id="success"></div>
      <div class="controls">
        <button class="btn btn-success" type="submit" class="form-control form-control-lg" class="btn btn-primary" id="send_button">Register</button>
      </div>
    </div>
  </fieldset>
</form>
</div>
<script>
$(document).ready(function(){
    $('#simple_form input, #simple_form textarea').jqBootstrapValidation({
		preventSubmit: true,
		submitSuccess: function($form, event){     
			event.preventDefault();
			$this = $('#send_button');
			$this.prop('disabled', true);
			var form_data = $("#simple_form").serialize();
			$.ajax({
			   url:"insert.php",
			   method:"POST",
			   data:form_data,
			   success:function(){
				$('#success').html("<div class='alert alert-success'><strong>Successfully Register. </strong></div>");
				$('#simple_form').trigger('reset');
			   },
			   error:function(){
				$('#success').html("<div class='alert alert-danger'>There is some error</div>");
				$('#simple_form').trigger('reset');
			   },
			   complete:function(){
				setTimeout(function(){
				 $this.prop("disabled", false);
				 $('#success').html('');
				}, 5000);
			   }
			});
		},
    });

});
</script>
</body>
</html>
insert.php
//insert.php
<?php
include('dbcon.php');
$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$sql = "INSERT INTO tbl_user(username, email, password) VALUES ('$username', '$email', '$password')"; 
$conn->query($sql);
echo "Record Successfully added";
?>
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 23, 2021

Python Flask Registration Form Validation using jqBootstrapValidation with Jquery Ajax and Mysql

Python Flask Registration Form Validation using jqBootstrapValidation with Jquery Ajax and Mysql


A JQuery validation plugin for bootstrap forms.

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

CREATE TABLE `tbl_user` (
  `id` int(11) NOT NULL,
  `username` varchar(150) NOT NULL,
  `email` varchar(150) NOT NULL,
  `password` varchar(150) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

--
-- Dumping data for table `tbl_user`
--

INSERT INTO `tbl_user` (`id`, `username`, `email`, `password`) VALUES
(1, 'cairocoders', 'cairodoers@gmail.com', 'tutorial101');

--
-- Indexes for dumped tables
--

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

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_user`
--
ALTER TABLE `tbl_user`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
app.py
 
#app.py
from flask import Flask, render_template, request, jsonify
from flask_mysqldb import MySQL,MySQLdb #pip install flask-mysqldb https://github.com/alexferl/flask-mysqldb

app = Flask(__name__)
        
app.secret_key = "caircocoders-ednalan"
        
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'testingdb'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
mysql = MySQL(app) 
                     
@app.route('/')
def index(): 
    return render_template('index.html')

@app.route("/insert",methods=["POST","GET"])
def insert():
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    if request.method == 'POST':
        username = request.form['username']
        email = request.form['email']
        password = request.form['password']
        cur.execute("INSERT INTO tbl_user (username, email, password) VALUES (%s,%s,%s)",[username,email,password])
        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 Registration Form Validation using jqBootstrapValidation with Jquery Ajax and Mysql</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/jqBootstrapValidation/1.3.6/jqBootstrapValidation.js"></script>
<style>
.controls p{
    color:#a94442;
}
</style>
</head>
<body>
<div class="container">
<br />
<h3 align="center">Python Flask Registration Form Validation using jqBootstrapValidation with Jquery Ajax and Mysql</h3>
<br />
<form class="form-horizontal" method="POST" id="simple_form" novalidate="novalidate">
  <fieldset>
    <div id="legend">
      <legend class="">Register</legend>
    </div>
    <div class="control-group">
      <label class="control-label"  for="username">Username</label>
      <div class="controls">
        <input type="text" id="username" name="username" class="form-control form-control-lg" placeholder="Name" required="required" data-validation-required-message="Please enter your Username">
        <p class="text-danger help-block"></p>
      </div>
    </div>
 
    <div class="control-group">
      <label class="control-label" for="email">E-mail</label>
      <div class="controls">
        <input type="email" id="email" name="email" class="form-control form-control-lg" placeholder="Email" required="required" data-validation-required-message="Please provide your E-mail">
        <p class="text-danger help-block"></p>
      </div>
    </div>
 
    <div class="control-group">
      <label class="control-label" for="password">Password</label>
      <div class="controls">
        <input type="password" id="password" name="password" class="form-control form-control-lg" placeholder="Password" required="required" data-validation-required-message="Please provide your password">
        <p class="text-danger help-block"></p>
      </div>
    </div>
 
    <div class="control-group">
      <label class="control-label"  for="password_confirm">Password (Confirm)</label>
      <div class="controls">
        <input type="password" id="password_confirm" class="form-control form-control-lg" name="password_confirm" placeholder="Password (Confirm)" required="required" data-validation-required-message="Please confirm password">
        <p class="text-danger help-block"></p>
      </div>
    </div>
 
    <div class="control-group">
		<div id="success"></div>
      <div class="controls">
        <button class="btn btn-success" type="submit" class="form-control form-control-lg" class="btn btn-primary" id="send_button">Register</button>
      </div>
    </div>
  </fieldset>
</form>
</div>
<script>
$(document).ready(function(){
    $('#simple_form input').jqBootstrapValidation({
		preventSubmit: true,
		submitSuccess: function($form, event){     
			event.preventDefault();
			$this = $('#send_button');
			$this.prop('disabled', true);
			var form_data = $("#simple_form").serialize();
			$.ajax({
			   url:"/insert",
			   method:"POST",
			   data:form_data,
			   success:function(){
				$('#success').html("<div class='alert alert-success'><strong>Successfully Register. </strong></div>");
				$('#simple_form').trigger('reset');
			   },
			   error:function(){
				$('#success').html("<div class='alert alert-danger'>There is some error</div>");
				$('#simple_form').trigger('reset');
			   },
			   complete:function(){
				setTimeout(function(){
				 $this.prop("disabled", false);
				 $('#success').html('');
				}, 5000);
			   }
			});
		},
    });

});
</script>
</body>
</html>

Monday, February 22, 2021

Displaying Popups data on mouse hover using Jquery Ajax and PHP Mysql database

Displaying Popups data on mouse hover using Jquery Ajax and PHP Mysql database

load dynamic data from the database using jqueryui tooltip

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

https://jqueryui.com/

Tooltip : https://jqueryui.com/tooltip/

--
-- 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,
  `photo` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

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

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

--
-- 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=19;
index.php
//index.php
<!DOCTYPE html>
<html>
<head>
<title>Displaying Popups data on mouse hover using Jquery Ajax and PHP Mysql database</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

<link rel="stylesheet" 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>
<body>  
<div class="container">
   <br />
   <h3 align="center">Displaying Popups data on mouse hover using Jquery Ajax and PHP Mysql database</a></h3><br />
   <br />
   <div class="row">
    <div class="col-md-12">
		<div class="panel-body">
			<div class="table-responsive">
                <table class="table table-bordered">
                    <thead>
                        <tr>
                            <th width="60">Photo</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><a href="#" id="'.$row["id"].'" title=" "><img src="images/'.$row["photo"].'" height="50" width="50"/></a></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>
    </div>
  </div>
<script>  
$(document).ready(function(){ 
	$('a').tooltip({
	  classes:{
	   "ui-tooltip":"highlight"
	  },
	  position:{ my:'left center', at:'right+50 center'},
	  content:function(result){
	   $.post('fetch_data.php', {
		id:$(this).attr('id')
	   }, function(data){
		result(data);
	   });
	  }
	});
});  
</script>
</body>  
</html> 
fetch_data.php
//fetch_data.php
<?php
include('dbcon.php');
if(isset($_POST["id"]))
{
	$result = $conn->query("SELECT * FROM employee WHERE id = '".$_POST["id"]."'");
	$output = '';
	foreach($result as $row)
	{
	  $output .= '
	  <p align="center"><img src="images/'.$row["photo"].'" class="img-thumbnail" /></p>
	  <p>Name : '.$row["name"].'</p>';
	}
	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);
}
?>

Displaying Popups data on mouse hover using Jquery Ajax and Python Flask Mysql database

Displaying Popups data on mouse hover using Jquery Ajax and Python Flask Mysql database

load dynamic data from the database using jqueryui tooltip

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

https://jqueryui.com/

Tooltip : https://jqueryui.com/tooltip/

--
-- 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,
  `photo` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

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

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

--
-- 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=19;

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 ASC")
    employeelist = cur.fetchall()
    return render_template('index.html', employeelist=employeelist)

@app.route("/fetchdata",methods=["POST","GET"])
def fetchdata():
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    if request.method == 'POST':
        id = request.form['id']
        cur.execute("SELECT * FROM employee WHERE id = %s", [id])
        rs = cur.fetchone() 
        name = rs['name']
        photo = rs['photo']
        print(photo)
    return jsonify({'htmlresponse': render_template('response.html', name=name, photo=photo)})

if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html>
<head>
<title>Displaying Popups data on mouse hover using Jquery Ajax and Python Flask Mysql database </title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

<link rel="stylesheet" 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>
<body>  
<div class="container">
   <br />
   <h3 align="center">Displaying Popups data on mouse hover using Jquery Ajax and Python Flask Mysql database </a></h3><br />
   <br />
   <div class="row">
    <div class="col-md-12">
		<div class="panel-body">
			<div class="table-responsive">
                <table class="table table-bordered">
                    <thead>
                        <tr>
                            <th width="60">Photo</th>
                            <th>Name</th>
                            <th>Position</th>
                            <th>Office</th>
                            <th>Age</th>
                            <th>Salary</th>
                        </tr>
                        </thead> 
                        {% for row in employeelist %}
                            <tr>
                                <td><a href="#" id="{{row.id}}" title=" "><img src="/static/images/{{row.photo}}" height="50" width="50"/></a></td>
                                <td>{{row.name}}</td>
                                <td>{{row.position}}</td>
                                <td>{{row.office}}</td>
                                <td>{{row.age}}</td>
                                <td>{{row.salary}}</td>
                            </tr>
                        {% endfor %} 
                </table>
            </div>
      </div>
     </div>
    </div>
  </div>
<script>  
$(document).ready(function(){ 
    $('a').tooltip({
        classes:{
            "ui-tooltip":"highlight"
        },
        position:{ my:'left center', at:'right+50 center'},
        content:function(result){
            $.post('/fetchdata', {
                id:$(this).attr('id')
            }, function(data){
                result(data.htmlresponse);
                
            });
        }
    });
});  
</script>
</body>  
</html> 
templates/response.html
//templates/response.html
<p align="center"><img src="/static/images/{{photo}}" class="img-thumbnail" /></p>
<p>Name : {{ name }}</p>

Sunday, February 21, 2021

Editable Select Box using PHP Mysql database and jQuery Ajax

Editable Select Box using PHP Mysql database and jQuery Ajax

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/

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

CREATE TABLE `tbl_user` (
  `userid` int(11) NOT NULL,
  `fullname` varchar(50) NOT NULL,
  `country` varchar(100) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
index.php
//index.php
<!DOCTYPE html>
<html>
<head>
<title>Editable Select Box using PHP Mysql database 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>

<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>  
<?php
include('dbcon.php');
$result = $conn->query("SELECT * FROM country ORDER BY country ASC");
?>
<div class="container">  
   <br />
   <h2 align="center">Editable Select Box using PHP Mysql database and jQuery Ajax</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">
       <?php
       foreach($result as $row)
       {
        echo '<option value="'.$row["country"].'">'.$row["country"].'</option>';
       }
       ?>
       </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.php",
				method:"POST",
				data:$(this).serialize(),
				success:function(data)
				{
				 alert(data);
				 $('#sample_form')[0].reset();
				}
		   });
		}
	});
});  
</script>
</body>  
</html> 
insert.php
//insert.php
<?php
include('dbcon.php');
$name = $_POST["name"];
$country = $_POST["country"];
$sql = "INSERT INTO tbl_user(fullname, country) VALUES ('$name', '$country')"; 
$conn->query($sql);
echo "Record Successfully added";
?>
insert.php
//dbcon.php
<?php
$conn = new mysqli('localhost','root','','testingdb');
if ($conn->connect_error) {
    die('Error : ('. $conn->connect_errno .') '. $conn->connect_error);
}
?>

Related Post