jQuery AJAX Image Upload in PHP


This example shows how to upload the image file using jQuery AJAX.

index.php
<html>
 <head>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
 </head>
 <body>
  <form>
   <p>Enter Name : <input type='text' name='name'></p>
   <p>Browse File : <input type='file' name='file' required></p>
   <p><input type='submit' value='Upload' id='upload'></p>
  </form>
  <p id='msg'></p>
  <script>
  $(document).ready(function(){
  	$("#upload").click(function(e){
	 e.preventDefault();
	 var form=$(this).closest("form");
	 formdata = new FormData(form[0]);
	 $.ajax({
	   url:'upload_file.php',
	   type: 'POST',
	   data:formdata ? formdata : form.serialize(),
	   cache: false,
	   contentType: false,
	   processData: false,
	   success: function(res){
	   	$("#msg").text(res);
	   }
	 });
  	});
  });
  </script>
 </body>
</html>
upload.php
<?php 
  $uploadMessage="";
  $uploadFolder="upload/";
  if(isset($_FILES["file"])){
  	
    $fileName=basename($_FILES["file"]["name"]); //Get File Name 
    $fileType=pathinfo($_FILES["file"]["name"],PATHINFO_EXTENSION);//Get File Extension
    $fileType=strtolower($fileType); //convert to lowercase
    $fileName=$_POST["name"].".".$fileType; //Set File name with Form value
    
    if(!is_dir($uploadFolder)){
      $uploadMessage="Upload Failed.Upload Folder not exists!!!";
    }
    else if(file_exists($fileName)){
      $uploadMessage="Upload Failed.File Already Exists!!!";
    }
    else if(move_uploaded_file($_FILES["file"]["tmp_name"],$uploadFolder.$fileName)){	
      $uploadMessage="File Upload Success";
    }
    echo $uploadMessage;
  }

?>

Demo :

Ajax Image Upload