How to upload Image file using AJAX and jQuery

In PHP you can easily upload any type file on the server using move_uploaded_file() method.

But it requires form submit for uploading the selected file.

If you want to store image file and display preview without reloading the whole page then you need to use jQuery AJAX.

Send the selected file using FormData object in AJAX request.

How to upload Image file using AJAX and jQuery


Contents

  1. HTML
  2. CSS
  3. PHP
  4. jQuery
  5. Conclusion

1. HTML

Create a <form > element where added <img >, file element and a button.

Image preview display in <img> after successfully upload using jQuery.

Completed Code

<div class="container">
    <form method="post" action="" enctype="multipart/form-data" id="myform">
        <div class='preview'>
            <img src="" id="img" width="100" height="100">
        </div>
        <div >
            <input type="file" id="file" name="file" />
            <input type="button" class="button" value="Upload" id="but_upload">
        </div>
    </form>
</div>

2. CSS

Hide the img element.

/* Container */
.container{
   margin: 0 auto;
   border: 0px solid black;
   width: 50%;
   height: 250px;
   border-radius: 3px;
   background-color: ghostwhite;
   text-align: center;
}
/* Preview */
.preview{
   width: 100px;
   height: 100px;
   border: 1px solid black;
   margin: 0 auto;
   background: white;
}

.preview img{
   display: none;
}
/* Button */
.button{
   border: 0px;
   background-color: deepskyblue;
   color: white;
   padding: 5px 15px;
   margin-left: 10px;
}

3. PHP

Create an upload.php file and upload directory for storing image files.

Check the file extension if it is valid then store the file and return the file location.

Completed Code

<?php

/* Getting file name */
$filename = $_FILES['file']['name'];

/* Location */
$location = "upload/".$filename;
$uploadOk = 1;
$imageFileType = pathinfo($location,PATHINFO_EXTENSION);

/* Valid Extensions */
$valid_extensions = array("jpg","jpeg","png");
/* Check file extension */
if( !in_array(strtolower($imageFileType),$valid_extensions) ) {
   $uploadOk = 0;
}

if($uploadOk == 0){
   echo 0;
}else{
   /* Upload file */
   if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){
      echo $location;
   }else{
      echo 0;
   }
}

4. jQuery

On the upload button click get the selected file and create a FormData object.

Append file in FormData object.

Send an AJAX request where pass the fd object and on successful callback check the response is 0 or not.

If it does not 0 then update the <img > source otherwise alert('file not uploaded') message.

On page load img element is set display: none;.

This element is getting displayed when a file is successfully uploaded with jQuery – $(".preview img").show();.

Completed Code

$(document).ready(function(){

    $("#but_upload").click(function(){

        var fd = new FormData();
        var files = $('#file')[0].files[0];
        fd.append('file',files);

        $.ajax({
            url: 'upload.php',
            type: 'post',
            data: fd,
            contentType: false,
            processData: false,
            success: function(response){
                if(response != 0){
                    $("#img").attr("src",response); 
                    $(".preview img").show(); // Display image element
                }else{
                    alert('file not uploaded');
                }
            },
        });
    });
});

5. Conclusion

Use FormData object to store the file and pass in the AJAX request for upload it.

In the PHP file access the file using $_FILES.

If you found this tutorial helpful then don't forget to share.

Related Post

Spread the love
  • 1
  •  
  •  
  •  
  •  
  •  

9 Comments

  1. Alessandro B. said:

    Thanks for this good how-to.
    After some hours of search on the net this article has resolved all my problems 🙂

    December 12, 2017
    Reply
  2. Jesús said:

    Thank you! It was very useful!

    May 13, 2018
    Reply
  3. Paul said:

    This is an awesome article, after days of efforts, this was the best solution I found

    May 18, 2018
    Reply
  4. deepak singh said:

    this post is great but i want to sent data also. how i send data and image at the same time?

    December 5, 2018
    Reply
    • Yogesh Singh said:

      Append data in FormData object.

      Example –

      var name = "yogesh";
      fd.append('name',name);

      On the AJAX file read it using $_POST[‘name’].

      December 5, 2018
      Reply
  5. sunil said:

    not working

    December 5, 2018
    Reply
    • Yogesh Singh said:

      Hi Sunil,
      Have you check browser console is any error displaying?

      December 6, 2018
      Reply
  6. Abhinav Singh said:

    Well Thanx for the codes the thing is that I just want to send only single image and m getting the error- Cannot read property ‘file’ of null I dont want to save multiple images i just need only one image

    December 11, 2018
    Reply
    • Yogesh Singh said:

      Hi Abhinav,
      In the example, I am already saving a single file.

      December 11, 2018
      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *