article

Showing posts with label web-development (jquery). Show all posts
Showing posts with label web-development (jquery). Show all posts

Thursday, September 7, 2023

PHP Mysql Comment Jquery Ajax

PHP Mysql Comment Jquery Ajax

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.7.0/dist/jquery.min.js

Database Table 
CREATE TABLE `msg` (
  `id` int(11) NOT NULL,
  `name` text NOT NULL,
  `msg` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
//index.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
	<link rel="stylesheet" href="style.css">
    <title>PHP Mysql Comment Jquery Ajax</title>
</head>
<body>
<div class="container mt-5">
    <div class="d-flex justify-content-center row">
        <div class="col-md-8">
            <div class="d-flex flex-column comment-section">
                <div class="bg-white p-2">
                    <div class="d-flex flex-row user-info"><img class="rounded-circle" src="https://i.imgur.com/RpzrMR2.jpg" width="40">
                        <div class="d-flex flex-column justify-content-start ml-2"><span class="d-block font-weight-bold name">Marry Andrews</span><span class="date text-black-50">Shared publicly - Jan 2020</span></div>
                    </div>
                    <div class="mt-2">
                        <p class="comment-text">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
                    </div>
                </div>
                <div class="bg-white">
                    <div class="d-flex flex-row fs-12">
                        <div class="like p-2 cursor"><i class="fa fa-thumbs-o-up"></i><span class="ml-1">Like</span></div>
                        <div class="like p-2 cursor"><i class="fa fa-commenting-o"></i><span class="ml-1">Comment</span></div>
                        <div class="like p-2 cursor"><i class="fa fa-share"></i><span class="ml-1">Share</span></div>
                    </div>
                </div>
				<form id="form">
                <div class="bg-light p-2">
                    <div class="d-flex flex-row align-items-start"><img class="rounded-circle" src="https://i.imgur.com/RpzrMR2.jpg" width="40">
					<input type="hidden" id="name" placeholder="Enter your name" value="Cairocoders Ednalan" required>
					<textarea class="form-control ml-1 shadow-none textarea" id="msg"></textarea>
					</div>
                    <div class="mt-2 text-right">
					<button class="btn btn-primary btn-sm shadow-none" type="button" id="btn">Post comment</button>
					<button class="btn btn-outline-primary btn-sm ml-1 shadow-none" type="button">Cancel</button>
					</div>
                </div>
				</form>
				<hr>
				<div class="content" id="content"></div>
            </div>
        </div>
    </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.7.0/dist/jquery.min.js"></script>
<script>
$(document).ready(function(){
    function loadData(){
        $.ajax({
            url: 'select-data.php',
            type: 'POST',
            success: function(data){
                $("#content").html(data);
            }
        });
    }

    loadData();

    $("#btn").on("click", function(e){
        e.preventDefault();
        var name = $("#name").val();
        var msg = $("#msg").val();

		$.ajax({
			url: 'insert-data.php',
            type: 'POST',
            data: {name: name, msg: msg},
            success: function(data){
                if (data == 1) {
                    loadData();
                    alert('Comment Submitted Successfully.');
                    $("#form").trigger("reset");
                }else {
                    alert("Comment Can't Submit.");
                }
            }
        });
    });
});
</script>
</body>
</html>
config.php
//config.php
<?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $database = "devdb";

    $conn = mysqli_connect($servername, $username, $password, $database);

    if (!$conn) {
        echo "Connection Failed.";
    }
?>
insert-data.php
//insert-data.php
<?php
    include 'config.php';

    $name = $_POST['name'];
    $msg = $_POST['msg'];
    
    $sql = "INSERT INTO msg (name, msg) VALUES ('$name', '$msg')";
    $result = mysqli_query($conn, $sql);

    if ($result) {
        echo 1;
    }else {
        echo 0;
    }
?>
select-data.php
//select-data.php
<?php
    include 'config.php';

    $sql = "SELECT * FROM msg ORDER BY id DESC";
    $result = mysqli_query($conn, $sql);

    if (mysqli_num_rows($result) > 0) {
        while ($row = mysqli_fetch_assoc($result)) {
?>
<div class="card mb-4">
    <div class="card-body">
		<p><?php echo $row['msg']; ?></p>
        <div class="d-flex justify-content-between">
            <div class="d-flex flex-row align-items-center">
                <img src="https://i.imgur.com/RpzrMR2.jpg" alt="avatar" width="25" height="25" />
                <p class="small mb-0 ms-2"><?php echo $row['name']; ?></p>
            </div>
        </div>
    </div>
</div>
<?php } } ?>
style.css
//style.css
body{background: #eee}
.date{font-size: 12px}
.comment-text{font-size: 14px}
.fs-12{font-size: 14px}
.shadow-none{box-shadow: none}
.name{color: #007bff}
.cursor:hover{color: blue}
.cursor{cursor: pointer}
.textarea{resize: none}

Wednesday, August 30, 2023

PHP Mysql Jquery Ajax Pagination

PHP Mysql Jquery Ajax Pagination

Create Database And Table
CREATE TABLE `country` (
  `id` int(6) NOT NULL,
  `country` varchar(250) NOT NULL DEFAULT ''
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_swedish_ci;

https://gist.github.com/adhipg/1600028#file-countries-sql

Create a Database Connection File db.php

//db.php
<?php
    $servername='localhost';
    $username='root';
    $password='';
    $dbname = "devdb";
    $conn=mysqli_connect($servername,$username,$password,"$dbname");
      if(!$conn){
          die('Could not Connect MySql Server:' .mysql_error());
        }
?>
Download simple-bootstrap-paginator Plugin https://github.com/jorgefernando1/simple-bootstrap-paginator

Create List File ajax-pagination.php
//ajax-pagination.php
<!DOCTYPE html>
<html>
<head>
    <title>PHP Mysql Jquery Ajax Pagination</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.7.0/dist/jquery.min.js"></script>
    <script src="simple-bootstrap-paginator.js"></script>
</head>
<body>
<div class="container">   
    <?php
        include_once("db.php");
        $perPage = 5;
        $sqlQuery = "SELECT * FROM country";
        $result = mysqli_query($conn, $sqlQuery);
        $totalRecords = mysqli_num_rows($result);
        $totalPages = ceil($totalRecords/$perPage);
    ?>
	<h2 class='w-100 d-flex justify-content-center p-3'>PHP Mysql Jquery Ajax Pagination</h2>
    <div class="row">
        <table class="table table-hover table-bordered">
            <thead>
                <tr>
                    <th>Id</th>
                    <th>Name</th>
                </tr>
            </thead>
            <tbody id="content">     
            </tbody>
        </table>   
        <div id="pagination"></div>    
        <input type="hidden" id="totalPages" value="<?php echo $totalPages; ?>">    
    </div>    
</div>
<script>
    $(document).ready(function(){
    var totalPage = parseInt($('#totalPages').val());   
    var pag = $('#pagination').simplePaginator({
        totalPages: totalPage,
        maxButtonsVisible: 5,
        currentPage: 1,
        nextLabel: 'Next',
        prevLabel: 'Prev',
        firstLabel: 'First',
        lastLabel: 'Last',
        clickCurrentPage: true,
        pageChange: function(page) {         
            $("#content").html('<tr><td colspan="6"><strong>loading...</strong></td></tr>');
            $.ajax({
                url:"get_data.php",
                method:"POST",
                dataType: "json",       
                data:{page: page},
                success:function(responseData){
					console.log(responseData);
                    $('#content').html(responseData.html);
                }
            });
        }
    });
});
</script>
</body>
</html>
Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.7.0/dist/jquery.min.js

Create Get Data PHP File get_data.php
// get_data.php
<?php
include_once("db.php");
$perPage = 10;
if (isset($_POST["page"])) { 
    $page  = $_POST["page"]; 
} else { 
    $page=1; 
};  
$startFrom = ($page-1) * $perPage;  
$sqlQuery = "SELECT * FROM country ORDER BY id ASC LIMIT $startFrom, $perPage";  
$result = mysqli_query($conn, $sqlQuery); 
$paginationHtml = '';
while ($row = mysqli_fetch_assoc($result)) {  
    $paginationHtml.='<tr>';  
    $paginationHtml.='<td>'.$row["id"].'</td>';
    $paginationHtml.='<td>'.$row["country"].'</td>';
    $paginationHtml.='</tr>';  
} 
$jsonData = array(
    "html"  => $paginationHtml,  
);
echo json_encode($jsonData); 
?>

Tuesday, February 21, 2023

PHP Mysql PDO CRUD Server Side Ajax DataTables

PHP Mysql PDO CRUD Server Side Ajax DataTables

Create database table 
CREATE TABLE `member` (
  `id` int(11) NOT NULL,
  `name` varchar(150) NOT NULL,
  `email` varchar(150) NOT NULL,
  `phone` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

datatables
https://datatables.net/
Add advanced interaction controls
to your HTML tables the free & easy way
index.php
//index.php
<!doctype html>
<head>
    <title>PHP Mysql PDO CRUD Server Side Ajax DataTables</title>
    <link rel="stylesheet" type="text/css" href="styles.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.2/css/jquery.dataTables.min.css">
</head>
<body>
<div class="container">
    <br />
    <h3 align="center">PHP Mysql PDO CRUD Server Side Ajax DataTables</h3>   
    <br />
    <div align="right">
		<button type="button" id="add_button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#userModal">
		  Add Member
		</button>
    </div>
    <br />	
    <table id="member_table" class="table table-striped">  
        <thead bgcolor="#6cd8dc">
            <tr class="table-primary">
                <th width="30%">ID</th>
                <th width="50%">Name</th>  
                <th width="30%">Email</th>
                <th width="30%">Phone</th>
                <th scope="col" width="5%">Edit</th>
                <th scope="col" width="5%">Delete</th>
            </tr>
        </thead>
    </table>
	
	<div class="modal" id="userModal" tabindex="-1">
	  <div class="modal-dialog">
		<div class="modal-content">
		  <div class="modal-header">
			<h5 class="modal-title">Add Member</h5>
			<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
		  </div>
		  <div class="modal-body">
			<form method="post" id="member_form" enctype="multipart/form-data">
				<div class="modal-body">
					<label>Enter Name</label>
					<input type="text" name="name" id="name" class="form-control" />
					<br />
					<label>Enter Email</label>
					<input type="email" name="email" id="email" class="form-control" />
					<br /> 
					<label>Enter Phone</label>
					<input type="text" name="phone" id="phone" class="form-control" />
					<br /> 
				</div>
				<div class="modal-footer">
					<input type="hidden" name="member_id" id="member_id" />
					<input type="hidden" name="operation" id="operation" />
					<input type="submit" name="action" id="action" class="btn btn-primary" value="Add" />
					<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
				</div>
			</form>
		  </div>
		</div>
	  </div>
	</div>
</div>  
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.13.2/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js"></script>
<script type="text/javascript" language="javascript" >
$(document).ready(function(){
    $('#add_button').click(function(){
        $('#member_form')[0].reset();
        $('.modal-title').text("Add New Details");
        $('#action').val("Add");
        $('#operation').val("Add");
    });
    
    var dataTable = $('#member_table').DataTable({
        "paging":true,
        "processing":true,
        "serverSide":true,
        "order": [],
        "info":true,
        "ajax":{
            url:"fetch.php",
            type:"POST"
               },
        "columnDefs":[
            {
                "targets":[0,3,4],
                "orderable":false,
            },
        ],    
    });

    $(document).on('submit', '#member_form', function(event){
        event.preventDefault();
        var id = $('#id').val();
        var name = $('#name').val();
        var email = $('#email').val();
        
        if(name != '' && email != '')
        {
            $.ajax({
                url:"insertupdated.php",
                method:'POST',
                data:new FormData(this),
                contentType:false,
                processData:false,
                success:function(data)
                {
                    $('#member_form')[0].reset();
                    $('#userModal').modal('hide');
                    dataTable.ajax.reload();
                }
            });
        }
        else
        {
            alert("Name, email Fields are Required");
        }
    });
    
    $(document).on('click', '.update', function(){
        var member_id = $(this).attr("id");
        $.ajax({
            url:"fetch_single.php",
            method:"POST",
            data:{member_id:member_id},
            dataType:"json",
            success:function(data)
            {
                $('#userModal').modal('show');
                $('#id').val(data.id);
                $('#name').val(data.name);
                $('#email').val(data.email);
                $('#phone').val(data.phone);
                $('.modal-title').text("Edit Member Details");
                $('#member_id').val(member_id);
                $('#action').val("Save");
                $('#operation').val("Edit");
            }
        })
    });
    
    $(document).on('click', '.delete', function(){
        var member_id = $(this).attr("id");
        if(confirm("Are you sure you want to delete this user?"))
        {
            $.ajax({
                url:"delete.php",
                method:"POST",
                data:{member_id:member_id},
                success:function(data)
                {
                    dataTable.ajax.reload();
                }
            });
        }
        else
        {
            return false;   
        }
    });
    
    
});
</script>             
</body>
</html>
db.php
//db.php
<?php
$connection = new PDO( 'mysql:host=localhost;dbname=projectdb', 'root', '' );
?>
//fetch.php
<?php
include('db.php');
include('function.php');
$query = '';
$output = array();
$query .= "SELECT * FROM member ";
if(isset($_POST["search"]["value"]))
{
	$query .= 'WHERE name LIKE "%'.$_POST["search"]["value"].'%" ';
	$query .= 'OR email LIKE "%'.$_POST["search"]["value"].'%" ';
} 

if(isset($_POST["order"]))
{
	$query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
}
else
{
	$query .= 'ORDER BY id ASC ';
}

if($_POST["length"] != -1)
{
	$query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
} 
$statement = $connection->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
$filtered_rows = $statement->rowCount();
foreach($result as $row)
{
	$sub_array = array();
	
	$sub_array[] = $row["id"];
	$sub_array[] = $row["name"];
	$sub_array[] = $row["email"];
	$sub_array[] = $row["phone"];
	$sub_array[] = '<button type="button" name="update" id="'.$row["id"].'" class="btn btn-primary btn-sm update"><i class="glyphicon glyphicon-pencil"> </i>Edit</button></button>';
	$sub_array[] = '<button type="button" name="delete" id="'.$row["id"].'" class="btn btn-danger btn-sm delete">Delete</button>';
	$data[] = $sub_array;
}
$output = array(
	"draw"				=>	intval($_POST["draw"]),
	"recordsTotal"		=> 	$filtered_rows,
	"recordsFiltered"	=>	get_total_all_records(),
	"data"				=>	$data
);
echo json_encode($output);
?>
function.php
//function.php
<?php
function get_total_all_records()
{
	include('db.php');
	$statement = $connection->prepare("SELECT * FROM member");
	$statement->execute();
	$result = $statement->fetchAll();
	return $statement->rowCount();
}
?>
insertupdated.php
//insertupdated.php
<?php
include('db.php');
include('function.php');
if(isset($_POST["operation"]))
{
	if($_POST["operation"] == "Add")
	{
		$statement = $connection->prepare("
			INSERT INTO member (name, email, phone) VALUES (:name, :email, :phone)");
		$result = $statement->execute(
			array(
				':name'	=>	$_POST["name"],
				':email'	=>	$_POST["email"],
				':phone'	=>	$_POST["phone"]
			)
		);
	}
	if($_POST["operation"] == "Edit")
	{
		$statement = $connection->prepare(
			"UPDATE member
			SET name = :name, email = :email, phone = :phone WHERE id = :id");
		$result = $statement->execute(
			array(
				':name'	=>	$_POST["name"],
				':email'	=>	$_POST["email"],
				':phone'	=>	$_POST["phone"],
				':id'			=>	$_POST["member_id"]
			)
		);
	}
}
?>
fetch_single.php
//fetch_single.php
<?php
include('db.php');
include('function.php');
if(isset($_POST["member_id"]))
{
	$output = array();
	$statement = $connection->prepare(
		"SELECT * FROM member WHERE id = '".$_POST["member_id"]."' LIMIT 1"
	);
	$statement->execute();
	$result = $statement->fetchAll();
	foreach($result as $row)
	{
		$output["id"] = $row["id"];
		$output["name"] = $row["name"];
		$output["email"] = $row["email"];
		$output["phone"] = $row["phone"];
	}
	echo json_encode($output);
}
?>
delete.php
//delete.php
<?php
include('db.php');
include('function.php');

if(isset($_POST["member_id"]))
{
	$statement = $connection->prepare(
		"DELETE FROM member WHERE id = :id"
	);
	$result = $statement->execute(

		array(':id'	=>	$_POST["member_id"])
		
	    );
}
?>

Friday, April 29, 2022

How to get PHP Session Value in jQuery

How to get PHP Session Value in jQuery

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js

getssionjquery.php
//getssionjquery.php
<!DOCTYPE html>
<html>
<head>
	<title>How to get PHP Session Value in jQuery</title>
	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" />
	<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
</head>
<body>
<?php session_start(); ?>
<div class="container">
	<h1 class="page-header text-center">How to get PHP Session Value in jQuery</h1>
	<div class="row">
		<div class="col-6">
			<h3>Set Session Value</h3>
			<form method="POST" action="session.php">
				<input type="text" name="session_value" class="form-control" placeholder="Input Value" required>
				<div style="margin-top:10px;">
				<button type="submit" class="btn btn-primary">Set Value</button> <a href="unset.php" type="button" class="btn btn-danger">Unset Value</a>
				</div>
			</form>
 
			<button type="button" id="checkSession" class="btn btn-info" style="margin-top:30px;">Check Session in jQuery</button>
		</div>
	</div>
 
	<input type="hidden" value="<?php
		if(isset($_SESSION['value'])){
			echo $_SESSION['value'];
		} 
	?>" id="session">
</div>
<script>
$(document).ready(function(){
	//check session
	$('#checkSession').click(function(){
		var session = $('#session').val();
		if(session == ''){
			alert('Session not Set');
			console.log('Session not Set');
		}
		else{
			alert('Current Session Value: '+session);
			console.log(session);
		}
	});
});
</script>
</body>
</html>
session.php
//session.php
<?php
	session_start();
 
	$session_value=$_POST['session_value'];
	$_SESSION['value']=$session_value;
 
	header('location:getsessionjquery.php');
?>
unset.php
//unset.php
<?php
	session_start();
	unset($_SESSION['value']);
	header('location:getsessionjquery.php');
?>

Monday, April 4, 2022

jQuery Preview Multiple Images

jQuery Preview Multiple Images

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js

index.html
//index.html
<!DOCTYPE html>
<html>
<head>
	<title>jQuery Preview Multiple Images</title>
	<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
	<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
	<style>
		.hidden{
			display:none;
		}
    	#preview{
    		margin-top:50px;
    	}    	
		#preview img {
    		margin:10px;
    	}
	</style>
</head>
<body>
<div class="container">
	<div class="row">
		<h2><center>jQuery Preview Multiple Images </center></h2>
		<input type="file" name="file" id="file" class="hidden" multiple>
		<center><button type="button" class="btn btn-primary" id="filebutton"><span id="filetext">Select File</span></button></center>
		<div id="preview"></div>	
	</div>
</div>
<script>
$(document).ready(function(){
	$('#filebutton').click(function(){
		$('#file').click();
	});

	$('#file').change(function(){

		var name = $(this).val().split('\\').pop();
		var file = $(this)[0].files;
		if(name != ''){
			if(file.length >=2){
				$('#filetext').html(file.length + ' files ready to upload');
			}
			else{
				$('#filetext').html(name);
			}
		}
	});

	$('#file').on("change", previewImages);
});

function previewImages() {

  var $preview = $('#preview').empty();
  if (this.files) $.each(this.files, readAndPreview);

  function readAndPreview(i, file) {
    
    if (!/\.(jpe?g|png|gif)$/i.test(file.name)){
      return alert(file.name +" is not an image");
    } // else...
    
    var reader = new FileReader();

    $(reader).on("load", function() {
      $preview.append($("<img>", {src:this.result, height:200}));
    });

    reader.readAsDataURL(file);
    
  }

}
</script>
</body>
</html>

Thursday, March 24, 2022

Jquery Ajax Image Upload with PHP MySQLi

Jquery Ajax Image Upload with PHP MySQLi

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js

CREATE TABLE `tbluploadphoto` (
  `photoid` int(11) NOT NULL,
  `location` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `tbluploadphoto`
  ADD PRIMARY KEY (`photoid`);


ALTER TABLE `tbluploadphoto`
  MODIFY `photoid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;


index.php
//index.php
<!DOCTYPE html>
<html>
<head>
    <title>Jquery Ajax Image Upload with PHP MySQLi</title>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" />
</head>
<body>
<div class="container">
  <div class="row">
      <form>
        <h2 align="center" style="color:blue">Jquery Ajax Image Upload with PHP MySQLi</h2>
        <label>Select Image:</label>
        <input type="file" name="file" id="file"><br>
        <button type="button" id="upload_button" class="btn btn-primary">Upload</button>
      </form>
  </div>
  <div style="width:80%; padding:auto; margin:auto;">
      <div id="imagelist"></div>
  </div>
</div>
<script>
$(document).ready(function(){

  showPhoto();

  $(document).on('click', '#upload_button', function(){
	  
    var name = document.getElementById("file").files[0].name;
    var form_data = new FormData();
    var ext = name.split('.').pop().toLowerCase();
    if(jQuery.inArray(ext, ['gif','png','jpg','jpeg']) == -1){
      alert("Invalid Image File");
    }
	
    var oFReader = new FileReader();
    oFReader.readAsDataURL(document.getElementById("file").files[0]);
    var f = document.getElementById("file").files[0];
    var fsize = f.size||f.fileSize;
	
    if(fsize > 2000000){
      alert("Image File Size is very big");
    }else{
		form_data.append("file", document.getElementById('file').files[0]);
		$.ajax({
		  url:"upload.php",
		  method:"POST",
		  data: form_data,
		  contentType: false,
		  cache: false,
		  processData: false,   
		  success:function(){
			showPhoto();
		  }
		});
    }
	
  });
});

function showPhoto(){
  $.ajax({
      url:"fetch_photo.php",
      method:"POST",
      data:{
        fetch:1,
      },
      success:function(data){
        $('#imagelist').html(data);
      }
    });
}
</script>
</body>
</html>
conn.php
//conn.php
<?php
$conn = mysqli_connect("localhost","root","","testingdb");
if (!$conn) {
	die("Connection failed: " . mysqli_connect_error());
}
?>
fetch_photo.php
//fetch_photo.php
<?php
	include('conn.php');
	if(isset($_POST['fetch'])){
		$inc=4;
		$query=mysqli_query($conn,"select * from tbluploadphoto");
		while($row=mysqli_fetch_array($query)){
		$inc = ($inc == 4) ? 1 : $inc+1; 
		if($inc == 1) echo '<div class="row">';  
 			?>
				<div class="col-lg-3"><img src="<?php echo $row['location']?>" style="height:200px; width:100%;"></div>
 
			<?php
		if($inc == 4) echo '</div>';
		}
		if($inc == 1) echo '<div class="col-lg-3"></div><div class="col-lg-3"></div><div class="col-lg-3"></div></div>'; 
		if($inc == 2) echo '<div class="col-lg-3"></div><div class="col-lg-3"></div></div>'; 
		if($inc == 3) echo '<div class="col-lg-3"></div></div>'; 
	}
?>
uppload.php
//uppload.php
<?php
include('conn.php');
if($_FILES["file"]["name"] != '')
{
 	$newFilename = time() . "_" . $_FILES["file"]["name"];
 	$location = 'upload/' . $newFilename;  
	move_uploaded_file($_FILES["file"]["tmp_name"], $location);
 	
 	mysqli_query($conn,"insert into tbluploadphoto (location) values ('$location')");
}
?>

Saturday, February 26, 2022

PHP Mysqli CRUD with JQuery AJAX and Bootstrap 5

PHP Mysqli CRUD (Create, Read, Update and Delete) with JQuery AJAX and Bootstrap 5

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js

Bootstrap icons
https://icons.getbootstrap.com/#install
https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css
index.php
//index.php
<?php
	include('conn.php');
?>
<!DOCTYPE html>
<html lang = "en">
	<head>
		<meta charset = "UTF-8" name = "viewport" content = "width-device=width, initial-scale=1" />
		<link rel = "stylesheet" type = "text/css" href = "https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" />
		<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css">
		<title>PHP Mysqli CRUD with JQuery AJAX and Bootstrap 5</title>
	</head>
<body>
	<div style="height:30px;"></div>
	<div class = "row">	
		<div class = "col-md-3">
		</div>
		<div class = "col-md-6 well">
			<div class="row">
                <div class="col-lg-12">
                    <center><h2 class = "text-primary">PHP Mysqli CRUD with JQuery AJAX and Bootstrap 5</h2></center>
					<hr>
				<div>
					<form>
						<div class="mb-3">
							<label>Firstname:</label>
							<input type  = "text" id = "firstname" class = "form-control">
						</div>
						<div class="mb-3">
							<label>Lastname:</label>
							<input type  = "text" id = "lastname" class = "form-control">
						</div>
						<div class="mb-3">
							<button type = "button" id="addnew" class = "btn btn-primary"><i class="bi bi-clipboard2-plus-fill"></i> Add</button>
						</div>
					</form>
				</div>
                </div>
            </div><br>
			<div class="row">
			<div id="userTable"></div>
			</div>
		</div>
	</div>
</body>
<script src = "https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>	
<script src = "https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
<script type = "text/javascript">
	$(document).ready(function(){
		showUser();
		//Add New
		$(document).on('click', '#addnew', function(){
			if ($('#firstname').val()=="" || $('#lastname').val()==""){
				alert('Please input data first');
			}
			else{
			$firstname=$('#firstname').val();
			$lastname=$('#lastname').val();				
				$.ajax({
					type: "POST",
					url: "addnew.php",
					data: {
						firstname: $firstname,
						lastname: $lastname,
						add: 1,
					},
					success: function(){
						showUser();
					}
				});
			}
		});
		//Delete
		$(document).on('click', '.delete', function(){
			$id=$(this).val();
				$.ajax({
					type: "POST",
					url: "delete.php",
					data: {
						id: $id,
						del: 1,
					},
					success: function(){
						showUser();
					}
				});
		});
		//Update
		$(document).on('click', '.updateuser', function(){
			$uid=$(this).val();
			$('#edit'+$uid).modal('hide');
			$('body').removeClass('modal-open');
			$('.modal-backdrop').remove();
			$ufirstname=$('#ufirstname'+$uid).val();
			$ulastname=$('#ulastname'+$uid).val();
				$.ajax({
					type: "POST",
					url: "update.php",
					data: {
						id: $uid,
						firstname: $ufirstname,
						lastname: $ulastname,
						edit: 1,
					},
					success: function(){
						showUser();
					}
				});
		});
	
	});
	
	//Showing our Table
	function showUser(){
		$.ajax({
			url: 'show_user.php',
			type: 'POST',
			async: false,
			data:{
				show: 1
			},
			success: function(response){
				$('#userTable').html(response);
			}
		});
	}
	
</script>
</html>
conn.php
//conn.php
<?php
$conn = mysqli_connect("localhost","root","","testingdb");
if (!$conn) {
	die("Connection failed: " . mysqli_connect_error());
}
?>
addnew.php
//addnew.php
<?php
	include('conn.php');
	if(isset($_POST['add'])){
		$firstname=$_POST['firstname'];
		$lastname=$_POST['lastname'];
		
		mysqli_query($conn,"insert into usertble (firstname, lastname) values ('$firstname', '$lastname')");
	}
?>
show_user.php
//show_user.php
<?php
	include('conn.php');
	if(isset($_POST['show'])){
		?>
		<table class = "table table-bordered alert-success table-hover">
			<thead>
				<th>Firstname</th>
				<th>Lastname</th>
				<th>Action</th>
			</thead>
				<tbody>
					<?php
						$quser=mysqli_query($conn,"select * from usertble");
						while($urow=mysqli_fetch_array($quser)){
							?>
								<tr>
									<td><?php echo $urow['firstname']; ?></td>
									<td><?php echo $urow['lastname']; ?></td>
									<td><button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#editModal<?php echo $urow['userid']; ?>"><i class="bi bi-pencil"></i> Edit</button> | <button class="btn btn-danger delete" value="<?php echo $urow['userid']; ?>"><i class="bi bi-trash"></i> Delete</button>
									<?php include('edit_modal.php'); ?>
									</td>
								</tr>
							<?php
						}
					
					?>
				</tbody>
			</table>
		<?php
	}

?>
edit_modal.php
//edit_modal.php
<div class="modal fade" id="edit<?php echo $urow['userid']; ?>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
	<?php
		$n=mysqli_query($conn,"select * from `user` where userid='".$urow['userid']."'");
		$nrow=mysqli_fetch_array($n);
	?>
  <div class="modal-dialog" role="document">
    <div class="modal-content">
		<div class = "modal-header">
			<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
			<center><h3 class = "text-success modal-title">Update Member</h3></center>
		</div>
		<form>
		<div class="modal-body">
			Firstname: <input type="text" value="<?php echo $nrow['firstname']; ?>" id="ufirstname<?php echo $urow['userid']; ?>" class="form-control">
			Lastname: <input type="text" value="<?php echo $nrow['lastname']; ?>" id="ulastname<?php echo $urow['userid']; ?>" class="form-control">
		</div>
		<div class="modal-footer">
			<button type="button" class="btn btn-default" data-dismiss="modal"><span class = "glyphicon glyphicon-remove"></span> Cancel</button> | <button type="button" class="updateuser btn btn-success" value="<?php echo $urow['userid']; ?>"><span class = "glyphicon glyphicon-floppy-disk"></span> Save</button>
		</div>
		</form>
    </div>
  </div>
</div>
update.php
//update.php
<?php
	include('conn.php');
	if(isset($_POST['edit'])){
		$id=$_POST['id'];
		$firstname=$_POST['firstname'];
		$lastname=$_POST['lastname'];
		
		mysqli_query($conn,"update usertble set firstname='$firstname', lastname='$lastname' where userid='$id'");
	}
?>
//delete.php
<?php
	include('conn.php');
	if(isset($_POST['del'])){
		$id=$_POST['id'];
		mysqli_query($conn,"delete from usertble where userid='$id'");
	}
?>

Saturday, April 17, 2021

Like Unlike using PHP Mysqli and jQuery AJAX

Like Unlike using PHP Mysqli and jQuery AJAX

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;


INSERT INTO `posts` (`id`, `title`, `content`, `link`, `timestamp`) VALUES
(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');


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

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

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

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

ALTER TABLE `like_unlike`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
index.php
//index.php
<!doctype html>
<html>
<head>
<title>Like Unlike using PHP Mysqli and jQuery AJAX</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />	
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function(){
    $(".like, .unlike").click(function(){
        var id = this.id;   
        var split_id = id.split("_");
        var text = split_id[0];
        var postid = split_id[1]; 
        var type = 0;
        if(text == "like"){
            type = 1;
        }else{
            type = 0;
        }
        $.ajax({
            url: 'likeunlike.php',
            type: 'post',
            data: {postid:postid,type:type},
            dataType: 'json',
            success: function(data){
                var likes = data['likes'];
                var unlikes = data['unlikes'];
                $("#likes_"+postid).text(likes);       
                $("#unlikes_"+postid).text(unlikes);   
                if(type == 1){
                    $("#like_"+postid).css("color","#ffa449");
                    $("#unlike_"+postid).css("color","lightseagreen");
                }
                if(type == 0){
                    $("#unlike_"+postid).css("color","#ffa449");
                    $("#like_"+postid).css("color","lightseagreen");
                }
            }
        });
    });
});
</script>
</head>
<body >
<div class="container" >
    <div class="row" style="padding:50px;">
		<p><h1>Like Unlike using PHP Mysqli and jQuery AJAX</h1></p>
        <div class="content">
            <?php
			include "dbcon.php";
                $userid = 5;
                $query = "SELECT * FROM posts";
                $result = mysqli_query($conn,$query);
                while($row = mysqli_fetch_array($result)){
                    $postid = $row['id'];
                    $title = $row['title'];
                    $conntent = $row['content'];
                    $type = -1;

                    $status_query = "SELECT count(*) as cntStatus,type FROM like_unlike WHERE userid=".$userid." and postid=".$postid;
                    $status_result = mysqli_query($conn,$status_query);
                    $status_row = mysqli_fetch_array($status_result);
                    $count_status = $status_row['cntStatus'];
                    if($count_status > 0){
                        $type = $status_row['type'];
                    }

                    $like_query = "SELECT COUNT(*) AS cntLikes FROM like_unlike WHERE type=1 and postid=".$postid;
                    $like_result = mysqli_query($conn,$like_query);
                    $like_row = mysqli_fetch_array($like_result);
                    $total_likes = $like_row['cntLikes'];

                    $unlike_query = "SELECT COUNT(*) AS cntUnlikes FROM like_unlike WHERE type=0 and postid=".$postid;
                    $unlike_result = mysqli_query($conn,$unlike_query);
                    $unlike_row = mysqli_fetch_array($unlike_result);
                    $total_unlikes = $unlike_row['cntUnlikes'];

            ?>
                    <div class="post">
                        <h1><?php echo $title; ?></h1>
                        <div class="post-text">
                            <?php echo $conntent; ?>
                        </div>
                        <div class="post-action">
                            <input type="button" value="Like" id="like_<?php echo $postid; ?>" class="like" style="<?php if($type == 1){ echo "color: #ffa449;"; } ?>" /> (<span id="likes_<?php echo $postid; ?>"><?php echo $total_likes; ?></span>) 
                            <input type="button" value="Unlike" id="unlike_<?php echo $postid; ?>" class="unlike" style="<?php if($type == 0){ echo "color: #ffa449;"; } ?>" /> (<span id="unlikes_<?php echo $postid; ?>"><?php echo $total_unlikes; ?></span>)
                        </div>
                    </div>
            <?php
                }
            ?>
        </div>
   </div>
</div>
<style>
.content{
    border: 0px solid black;
    border-radius: 3px;
    padding: 5px;
    margin: 0 auto;
    width: 70%;
}
.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-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>
likeunlike.php
//likeunlike.php
<?php
include "dbcon.php";
$userid = 7;
$postid = $_POST['postid'];
$type = $_POST['type'];

$query = "SELECT COUNT(*) AS cntpost FROM like_unlike 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 like_unlike(userid,postid,type) values(".$userid.",".$postid.",".$type.")";
    mysqli_query($conn,$insertquery);
}else {
    $updatequery = "UPDATE like_unlike SET type=" . $type . " where userid=" . $userid . " and postid=" . $postid;
    mysqli_query($conn,$updatequery);
}

$query = "SELECT COUNT(*) AS cntLike FROM like_unlike WHERE type=1 and postid=".$postid;
$result = mysqli_query($conn,$query);
$fetchlikes = mysqli_fetch_array($result);
$totalLikes = $fetchlikes['cntLike'];

$query = "SELECT COUNT(*) AS cntUnlike FROM like_unlike WHERE type=0 and postid=".$postid;
$result = mysqli_query($conn,$query);
$fetchunlikes = mysqli_fetch_array($result);
$totalUnlikes = $fetchunlikes['cntUnlike'];

$return_arr = array("likes"=>$totalLikes,"unlikes"=>$totalUnlikes);

echo json_encode($return_arr);
?>
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);
}
?>

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);
}
?>

Friday, February 19, 2021

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

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

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

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

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

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

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

--
-- Indexes for dumped tables
--

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

--
-- AUTO_INCREMENT for dumped tables
--

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

Product Filters Price Range Using PHP Mysql and Jquery Ajax

Product Filters Price Range Using PHP Mysql and Jquery Ajax

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

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

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

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

--
-- Indexes for dumped tables
--

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

--
-- AUTO_INCREMENT for dumped tables
--

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

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

Wednesday, February 17, 2021

Jquery Ajax PHP Mysql File Upload Progress Bar

Jquery Ajax PHP Mysql File Upload Progress Bar

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

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

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

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

--
-- Indexes for dumped tables
--

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

--
-- AUTO_INCREMENT for dumped tables
--

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

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

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

Monday, February 15, 2021

PHP Mysql and Jquery Ajax Data Live Search Multi Select Dropdown

PHP Mysql and Jquery Ajax Data Live Search Multi Select Dropdown

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


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

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

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

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

--
-- Indexes for dumped tables
--

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

--
-- AUTO_INCREMENT for dumped tables
--

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

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

Related Post