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.

Spread the love
  • 1
  •  
  •  
  •  
  •  

21 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
  7. Juan Carlos said:

    Thanks Yogesh Singh for your recommendations clear and works fine

    January 21, 2019
    Reply
  8. joseph said:

    Hi Yogesh, nice tutorial there, but it’s not working for me.
    Console throws an error ,”append called on an object that does not implement interface FormData”

    January 23, 2019
    Reply
  9. Luke said:

    This works really nicely. How would I go about uploading multiple files from a single input field? (E.g., ) When I try, it only keeps the data for the last image in the list.

    I tried looping through the files, but to no avail. I had replaced these lines:
    var files = $(‘#$input_id’)[0].files[0];
    formData.append(‘file’,files);

    with:

    $.each($(‘#file’)[0].files, function(i, file) {
    fd.append(‘file’, file);
    });

    and:

    var upl = $(‘#file’).files.length;
    for (var x = 0; x < upl; x++) {
    fd.append('file', $('#file').files[x]);
    }

    But only the last image in the list would be saved to FormData. Any ideas?

    January 31, 2019
    Reply
  10. Luke said:

    I figured a way to allow multiple uploads from a single input field:
    Replace:
    var files = $(‘#file’)[0].files[0];
    fd.append(‘file’,files);

    with this:

    var input = $(‘#file’)[0];
    $.each(input.files, function(i, file) {
    // add each file to ‘files’ element in
    fd.append(‘files[]’, file);
    });

    $.each() runs through each of the files selected in the field. Make sure you’ve set a key name with “[]” so it will accept multiple files.

    February 1, 2019
    Reply
    • Yogesh Singh said:

      That’s great you figure out on your own. I will try to publish a tutorial on this topic soon.

      February 1, 2019
      Reply
  11. peter said:

    please using Jquery, how do i send the image and another parameter e.g an ID

    February 2, 2019
    Reply
  12. peter said:

    how do i pass another parameter with the image using jquery please

    February 2, 2019
    Reply
    • Yogesh Singh said:

      Hi Peter,
      You need to append data in FormData object.

      Example –

      fd.append(‘ID’,121);

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

      February 2, 2019
      Reply
  13. Laurent said:

    Hi Yogesh Singh

    Thank so much ! It’s perfectly clear !

    Thanks agani and have a nice day !!

    Laurent

    February 6, 2019
    Reply

Leave a Reply

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