How to Uploading an image file using ajax, Jquery and PHP
How to Uploading an image file using ajax, Jquery and PHP
Uploading files from clients to servers is one of the important features of any PHP application. However, the implementation of features with proper security and hassle-free configuration could be tricky. Developers could use several PHP file upload scripts to ensure that the application offers this feature seamlessly.
To download full project click here to download
Soures Code
- Create index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>How to upload Image file using AJAX and jQuery</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script src="jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#but_upload").click(function(){
var fd = new FormData();
var files = $('#file')[0].files;
// Check file selected or not
if(files.length > 0 ){
fd.append('file',files[0]);
$.ajax({
url:'upload.php',
type:'post',
data:fd,
contentType: false,
processData: false,
success:function(response){
if(response != 0){
$("#img").attr("src",response);
$('.preview img').show();
}else{
alert('File not uploaded');
}
}
});
}else{
alert("Please select a file.");
}
});
});
</script>
</head>
<body>
<div class="container">
<form method="post" action="" enctype="multipart/form-data" id="myform">
<div class='preview'>
<img src="upload/default.png" id="img" width="100" height="100">
</div>
<div >
<input type="file" id="file" name="file" />
<input type="button" class="button" value="Upload" id="but_upload">
</div>
</form>
</div>
</body>
</html>
- Create style.css
/* Container */
.container{
margin: 0 auto;
border: 0px solid black;
width: 50%;
height: 250px;
border-radius: 3px;
background-color: ghostwhite;
text-align: center;
}
/* Preview */
.preview{
width: 100px;
height: 100px;
border: 1px solid black;
margin: 0 auto;
background: white;
}
.preview img{
display: none;
}
/* Button */
.button{
border: 0px;
background-color: deepskyblue;
color: white;
padding: 5px 15px;
margin-left: 10px;
}
- Then create upload.php
<?php
if(isset($_FILES['file']['name'])){
/* Getting file name */
$filename = $_FILES['file']['name'];
/* Location */
$location = "upload/".$filename;
$imageFileType = pathinfo($location,PATHINFO_EXTENSION);
$imageFileType = strtolower($imageFileType);
/* Valid extensions */
$valid_extensions = array("jpg","jpeg","png");
$response = 0;
/* Check file extension */
if(in_array(strtolower($imageFileType), $valid_extensions)) {
/* Upload file */
if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){
$response = $location;
}
}
echo $response;
exit;
}
echo 0;
To download full project click here to download
Screenshots

