article

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

Related Post