In this post we have discuss one of the topic of based on ajax which is how to upload file or image without using Form Submit with Ajax request and PHP Script without page refresh.

For Upload Image, We have first select Image and when we have select image then Image will be uploaded to it’s define location. Because we have use jquery change event on input type file element.

In this we have also perform some validation like allowed image type and size of selected image also. This all validation we will perform also done by jquery.

For sending selected image to server we have use FormData() object. By using FormData() object we have send selected Image for server by using Ajax request. So by using FormData() Object and Ajax we have send selected file to PHP script. By using PHP Script we can upload selected file or Image to server without refresh of page.

After done uploading selected Image we have also uploaded image on web page without refreshing of page. So this is our simple tutorial on How to Upload Image without using Form Submit in Ajax PHP.

Source Code


<!DOCTYPE html>
  <title>Webslesson Tutorial | Upload File without using Form Submit in Ajax PHP</title>
  <script src=""></script>
  <link rel="stylesheet" href="" />
  <script src=""></script>
  <br /><br />
  <div class="container" style="width:700px;">
   <h2 align="center">Upload File without using Form Submit in Ajax PHP</h2>
   <br />
   <label>Select Image</label>
   <input type="file" name="file" id="file" />
   <br />
   <span id="uploaded_image"></span>

 $(document).on('change', '#file', function(){
  var name = document.getElementById("file").files[0].name;
  var form_data = new FormData();
  var ext = name.split('.').pop().toLowerCase();
  if(jQuery.inArray(ext, ['gif','png','jpg','jpeg']) == -1) 
   alert("Invalid Image File");
  var oFReader = new FileReader();
  var f = document.getElementById("file").files[0];
  var fsize = f.size||f.fileSize;
  if(fsize > 2000000)
   alert("Image File Size is very big");
   form_data.append("file", document.getElementById('file').files[0]);
    data: form_data,
    contentType: false,
    cache: false,
    processData: false,
     $('#uploaded_image').html("<label class='text-success'>Image Uploading...</label>");


if($_FILES["file"]["name"] != '')
 $test = explode('.', $_FILES["file"]["name"]);
 $ext = end($test);
 $name = rand(100, 999) . '.' . $ext;
 $location = './upload/' . $name;  
 move_uploaded_file($_FILES["file"]["tmp_name"], $location);
 echo '<img src="'.$location.'" height="150" width="225" class="img-thumbnail" />';