jQuery Ajax File Upload Without Page Refresh in PHP

Course- PHP Tutorial >

This is a very simple script used to upload single image file without page refresh using jQuery, Ajax and PHP. Here the user have option to set upload file format and set maximum file size. You need two jQuery files jquery.js and jquery.form.js to run this script. click here to upload multiple files. 

Include .js  Files

<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.form.js"></script>

 

Create the HTML Form

<form class="uploadform" method="post" enctype="multipart/form-data" 
action='upload.php'>
Upload your image <input type="file" name="imagefile" />
<input type="submit" value="Submit" name="submitbtn" id="submitbtn">
</form>
<!-- The uploaded image will display here -->
<div id='viewimage'></div>

 

JavaScript Code

<script type="text/javascript" >
$(document).ready(function() {
$('#submitbtn').click(function() {
$("#viewimage").html('');
$("#viewimage").html('<img src="img/loading.gif" />');
$(".uploadform").ajaxForm({
target: '#viewimage'
}).submit();
});
});
</script>

 

PHP File upload script

<?php
$file_formats = array("jpg", "png", "gif", "bmp"); // Set File format
$filepath = "upload_images/";

if ($_POST['submitbtn']=="Submit") {
  $name = $_FILES['imagefile']['name'];
  $size = $_FILES['imagefile']['size'];

   if (strlen($name)) {
      $extension = substr($name, strrpos($name, '.')+1);
      if (in_array($extension, $file_formats)) { 
          if ($size < (2048 * 1024)) {
             $imagename = md5(uniqid().time()).".".$extension;
             $tmp = $_FILES['imagefile']['tmp_name'];
             if (move_uploaded_file($tmp, $filepath . $imagename)) {
		 echo '<img class="preview" alt="" src="'.$filepath.'/'. 
			$imagename .'" />';
	     } else {
		 echo "Could not move the file.";
	     }
	  } else {
		echo "Your image size is bigger than 2MB.";
	  }
       } else {
	       echo "Invalid file format.";
       }
  } else {
       echo "Please select image..!";
  }
exit();
}

?>