Image upload in PHP using Ajax and jQuery

Rahul Ranjan
 2nd Apr, 2020
  120 Comments
Image upload in PHP using Ajax and jQuery

In this article, we are going to learn how to upload an image on the server without reloading the Web Page. Uploading image without page reload, optimize website performance and make it easy for user to interact with website components. So, here we will write a simple script to upload an image using Ajax and will display image on the same page after uploading.

We will create a page with form to select file from local storage or device. After that we will write small jQuery script to send the data to the server using AJAX. Once the data is received on the server, it needs to be validated and stored on the server and the output is sent back to the form script as response. You can see the demo of the article using button below: 

Demo

Let us get started. Firstly, we will create a simple html form to accept image file as input.

<div class="container">
<form id="uploadForm" method="post" enctype="multipart/form-data">
<div id="preview_area">Preview</div>
<div id="uploadFormLayer">
<span>Select an image:</span>
<input name="image" type="file" class="select_image" accept=".jpg,.png,.jpeg,.gif"/><br>
<div class="imgSubmit"><input name="image_upload" type="submit" value="Upload Image" /></div>
</form>
</div>
</div>

Here in above code, we have created a form with a input type file to accept image input from user and a submit button to upload image on server. we have also added 'accept' attribute on file input to restrict user from selecting any non-image file by mistake.
Now we will write a script to submit form data on to the server. For this firstly we will need to include jQuery library in our file and then below jQuery library we will write out script to upload image using AJAX.

<script src="js/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function (e) {
 $("#uploadForm").on('submit',(function(e) {
  e.preventDefault();  
  $("#preview_area").html('<img class="preview" src="loader.gif" alt="Uploaded Image" />');
  $.ajax({
         url: "upload.php",
         type: "POST",
         data:  new FormData(this),
         contentType: false,
         cache: false,
         processData:false,
         success: function(data)
     {
            $("#preview_area").html(data);
     }
   });
      return false;
   }));
});
</script>

Here in above code, we have added function to be triggered on submit event of the form. Once the submit button is clicked from the form, preview box will be filled with a temporary loading window. Then ajax function gets called which passes the data to the defined url
using the post method. Once the response is received from the url, loading window is  replaced with the output.

Below i have added both form and script with some extra tweak. Copy the code written below into a file and save it as index.php.

index.php

<html>
<head>
<title>Demo | Image Upload in PHP using Ajax and jQuery</title>
<link href="css/styles.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function (e) {
 $("#uploadForm").on('submit',(function(e) {
  e.preventDefault();  
  $("#preview_area").html('<img class="preview" src="loader.gif" alt="Uploaded Image" />');
  $.ajax({
   url: "upload.php",
   type: "POST",
   data:  new FormData(this),
   contentType: false,
   cache: false,
   processData:false,
   success: function(data)
      {
    $("#preview_area").html(data);
      }        
  });
  return false;
 }));
});
</script>
</head>
<body>
<div class="header">
 <a href="https://7topics.com/image-upload-in-php-using-ajax-and-jquery.html">Go back to the article</a>
</div>
<div class="container">
<form id="uploadForm" method="post" enctype="multipart/form-data">
<div id="preview_area">Preview</div>
<div id="uploadFormLayer">
<span>Select an image:</span>
<input name="image" type="file" class="select_image" accept="image/*"/><br>
<div class="imgSubmit"><input name="image_upload" type="submit" value="Upload Image" /></div>
</form>
</div>
</div>
<div class="footer">
 <div>Copyright &copy; 2016-2020 <a href="https://7topics.com">7topics.com</a></div>
</div>
</body>
</html>

As we have created our html structure, now we will add some styles to our structure to make it more attractive. Copy and paste below code in new page and save it as style.css

style.css

body {
   font-family: Arial;
   font-size: 14px;
   background:#ddd;
   margin:0px;
   padding:0px;
}
.header{
   width: 100%;
   background: #fff;
   height: 40px;
   margin-bottom: 10px;
}
.header>a{
   float: right;
   padding: 10px 10px;
}
.container {
   background:#fff;
   max-width: 320px;
   height: auto;
   margin: 0px auto;
   padding: 15px 0;
   border: 2px dashed #7b8bd6;
}
#preview_area{
   margin: 0px auto;
   width: 150px;
   height: 150px;
   text-align: center;
   line-height: 150px;
   font-weight: bold;
   color: #faf8ff;   
   border: 2px solid #096497;
   background-color: #6988be;
}
.preview {   
   width:150px;
   height:150px;
}
#uploadFormLayer{
   margin: 0px auto;
   max-width: 250px;
   padding: 25px 0 10px;
}
#uploadFormLayer>span{
    font-weight:bold;
}
.select_image {
   padding: 5px;
}
.imgSubmit>input{
   background:none;
   border:0;
   cursor:pointer;
   font-size:16px;
   width: 120px;
   margin: 20px auto 0;
   padding: 5px 10px;
   color:#fff;
   background-color: #263a7c;
   border: #0b0624 1px solid;
   border-bottom: 4px solid #140736;
}
.imgSubmit {
   text-align: center;
}
.imgSubmit>input:hover {
   background-color: #1c2647;
}
.footer{
   bottom: 0px;
   position: absolute;
   height: 35px;
   background: #fff;
   width: 100%;
   text-align: center;
}
.footer>div{
   padding: 10px 0;
}


Once the file is received on the server it needs to be validated and saved on the server. So copy below code in a file and save it as upload.php.

upload.php

<?php
if(isset($_FILES['image']['tmp_name'])) {
 $uploaded_image=$_FILES["image"]["name"];
 $validextensions = array("jpeg", "jpg", "png", "gif");
 $split_name=explode(".", $uploaded_image);
 $file_extension = strtolower($split_name[count($split_name)-1]);
 if(in_array($file_extension, $validextensions)){
  if(is_uploaded_file($_FILES['image']['tmp_name'])) {
  $sourcePath = $_FILES['image']['tmp_name'];
  $targetPath = "upload/".$_FILES['image']['name'];
  if(move_uploaded_file($sourcePath,$targetPath)) {
  ?>
  <img class="preview" src="<?php echo $targetPath; ?>" alt="Uploaded Image" />
  <?php
  }
  }  
 }else{
  echo "Not an image";
 } 
}else{
 echo "Select an image"; 
}
?>

Here in above code firstly we are checking if the file data is set, then we verify if the uploaded file is a valid image file. For that we are checking the extension of the uploaded image. If the image format is valid, then it gets uploaded on to the server and the output is sent back to the script as response with url of the image.

You can download above source code using button below:

Download

Thank you for reading my article, i hope that you liked this article. For any doubts or any request you can put your important feedback in the comment box below.

Related Tags
Php
Author Of The Post