Wednesday 22 February 2017

Upload File without using Form Submit in Ajax PHP



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


index.php



<!DOCTYPE html>
<html>
 <head>
  <title>Webslesson Tutorial | Upload File without using Form Submit in Ajax PHP</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
 </head>
 <body>
  <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>
  </div>
 </body>
</html>

<script>
$(document).ready(function(){
 $(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();
  oFReader.readAsDataURL(document.getElementById("file").files[0]);
  var f = document.getElementById("file").files[0];
  var fsize = f.size||f.fileSize;
  if(fsize > 2000000)
  {
   alert("Image File Size is very big");
  }
  else
  {
   form_data.append("file", document.getElementById('file').files[0]);
   $.ajax({
    url:"upload.php",
    method:"POST",
    data: form_data,
    contentType: false,
    cache: false,
    processData: false,
    beforeSend:function(){
     $('#uploaded_image').html("<label class='text-success'>Image Uploading...</label>");
    },   
    success:function(data)
    {
     $('#uploaded_image').html(data);
    }
   });
  }
 });
});
</script>


upload.php



<?php
//upload.php
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" />';
}
?>

36 comments:

  1. code not work still say Image Uploading...

    ReplyDelete
  2. formData doesn't work in IE and Safari..

    ReplyDelete
  3. Very Helpful & Easy To Learn From Webslesson Tutorial.

    ReplyDelete
  4. in ajax how to send more than one data ,please give me example

    ReplyDelete
  5. in ajax how to send more than one data ,please give me example

    ReplyDelete
  6. It's Working. Thank you

    ReplyDelete
  7. Nice ... work great. ...but, How to check if file already exist ?

    ReplyDelete
  8. Works like a charm !! THANKS !!!

    ReplyDelete
  9. hey. On 3th line "Cannot read property 'name' of undefined". Any idea?

    ReplyDelete
  10. Appreciated 'n Much Thanks

    ReplyDelete
  11. Makasih banyak atas solusinya ...

    ReplyDelete
  12. works, but the upload change the oietaion... original portrait to landscape...
    How can i fix this?

    ReplyDelete
  13. Thanks works, but how can i save the right orientation? read the EFIX-information...

    ReplyDelete
  14. Works perfectly. Thanks But is there a way i can send like a text in addition to the image to php?

    ReplyDelete
  15. This is so helpful. Thanks!

    ReplyDelete
  16. It works. I need to change this script to fit Codeigniter. Can you help?

    ReplyDelete
  17. sir the image is disappear after the refresh how to fix it

    ReplyDelete
  18. Localhost Database table name ... Reply sir..

    ReplyDelete
  19. Thanks so much, this little code is perfect for dynamic DOM.

    ReplyDelete
  20. Merci beaucoup j'ai utiliser ton code et crois moi il mâche super bien

    ReplyDelete
  21. it's Working fine , but I have 2 file to upload in same page, I try to rename ID
    < input type="file" name="file1" id="file1" / >
    < input type="file" name="file2" id="file2" / >

    ReplyDelete