Easy Ajax Image Upload with jQuery, PHP

In this tutorial we have a simple script which will Upload an Image using jQuery Ajax with PHP, we have simple file uploading tutorial on this blog but how about using ajax, it is very simple to upload an image to the server via jQuery ajax() without refreshing the whole page, once an image was uploaded it will be viewed on the same page. PHP code was used at the back-end which will select and upload an image and the uploading process will be done by ajax() method, let’s see ajax php image upload example.

Easy Ajax Image Upload with jQuery, PHP without Page Refresh

 

there are only 3 files we need for this tutorial, simple HTML form to accept valid image file, php file to upload selected image to the server side and javascript code to upload image easily without reloading page and to view the uploaded file into the particular div.

index.php

simple file contains only html form to accept image file to upload and send the request to the PHP file called “ajaxupload.php” via ajax() method.


<!doctype html>
<html>
<head lang="en">
 <meta charset="utf-8">
 <title>Easy Ajax Image Upload with jQuery and PHP - codingcage.com</title>
    <link rel="stylesheet" href="style.css" type="text/css" />
 <script type="text/javascript" src="js/jquery-1.11.3-jquery.min.js"></script>
 <script type="text/javascript" src="js/script.js"></script>
</head>
<body>
<div class="container">
 <h1><a href="">Easy Ajax Image Upload with jQuery</a></h1>
 <hr> 
 <div id="preview"><img src="no-image.jpg" /></div>
    
 <form id="form" action="ajaxupload.php" method="post" enctype="multipart/form-data">
  <input id="uploadImage" type="file" accept="image/*" name="image" />
  <input id="button" type="submit" value="Upload">
 </form>
    <div id="err"></div>
 <hr>
 <p><a href="http://www.codingcage.com" target="_blank">www.codingcage.com</a></p>
</div>
</body>
</html>

ajaxupload.php

this file contains only PHP code which will upload an image to the directory “uploads/” via ajax, here i have given the validation for the image and it will upload only valid extension images.

<?php

$valid_extensions = array('jpeg', 'jpg', 'png', 'gif', 'bmp'); // valid extensions
$path = 'uploads/'; // upload directory

if(isset($_FILES['image']))
{
 $img = $_FILES['image']['name'];
 $tmp = $_FILES['image']['tmp_name'];
  
 // get uploaded file's extension
 $ext = strtolower(pathinfo($img, PATHINFO_EXTENSION));
 
 // can upload same image using rand function
 $final_image = rand(1000,1000000).$img;
 
 // check's valid format
 if(in_array($ext, $valid_extensions)) 
 {     
  $path = $path.strtolower($final_image); 
   
  if(move_uploaded_file($tmp,$path)) 
  {
   echo "<img src='$path' />";
  }
 } 
 else 
 {
  echo 'invalid file';
 }
}

?>


script.js

Simple jQuery/JavaScript code to upload and view image without page refresh. using $.ajax() method an image file wil be send to the “ajaxupload.php” file and file will be uploaded and viewed at the same time.

$(document).ready(function (e) {
 $("#form").on('submit',(function(e) {
  e.preventDefault();
  $.ajax({
         url: "ajaxupload.php",
   type: "POST",
   data:  new FormData(this),
   contentType: false,
         cache: false,
   processData:false,
   beforeSend : function()
   {
    //$("#preview").fadeOut();
    $("#err").fadeOut();
   },
   success: function(data)
      {
    if(data=='invalid file')
    {
     // invalid file format.
     $("#err").html("Invalid File !").fadeIn();
    }
    else
    {
     // view uploaded file.
     $("#preview").html(data).fadeIn();
     $("#form")[0].reset(); 
    }
      },
     error: function(e) 
      {
    $("#err").html(e).fadeIn();
      }          
    });
 }));
});

that’s it, how it becomes easy to upload an image to the server via ajax code, feel free to contact me regarding this tutorial, hope you like it.