How to upload Image file using AJAX and jQuery

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

But it requires a form submit for uploading the selected file.

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

Send the selected file using the FormData object in the AJAX request.

How to upload Image file using AJAX and jQuery


Contents

  1. HTML
  2. CSS
  3. PHP
  4. jQuery
  5. Output
  6. 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 folder to store image files.

Read file extension. Initialized $valid_extensions Array with image extensions.

Check if file extension exists in $valid_extensions Array or not. If exists then assign file location to $response variable.

Return $response variable.

Completed Code

<?php

if(isset($_FILES['file']['name'])){

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

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

   /* Valid extensions */
   $valid_extensions = array("jpg","jpeg","png");

   $response = 0;
   /* Check file extension */
   if(in_array(strtolower($imageFileType), $valid_extensions)) {
      /* Upload file */
      if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){
         $response = $location;
      }
   }

   echo $response;
   exit;
}

echo 0;

4. jQuery

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

Check if a file is selected or not. If not selected then alert("Please select a file.") otherwise, append files[0] to 'file' key in fd.

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

If it is 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;
        
        // Check file selected or not
        if(files.length > 0 ){
           fd.append('file',files[0]);

           $.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');
                 }
              },
           });
        }else{
           alert("Please select a file.");
        }
    });
});

5. Output

View Output


5. Conclusion

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

In the PHP file access the file using $_FILES.

You can view this tutorial to know how to upload multiple files using jQuery AJAX.

If you found this tutorial helpful then don't forget to share.
Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request.

62 thoughts on “How to upload Image file using AJAX and jQuery”

  1. 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

    Reply
  2. 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”

    Reply
  3. 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?

    Reply
  4. 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.

    Reply
  5. I am getting the following error:
    Access to XMLHttpRequest at ‘url here’ from origin ‘http://127.0.0.1:5501’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

    Reply
  6. Hii
    i have code like this i am binding ajax response to a table but i had a image tag how i bind data form ajax to direct in Src of that image (Please check var ntd in the code)
    my code is like this
    for (var i = 0; i < data.length; i++) {
    if (data[i].invoicedetails != "") {
    var td = '’ + data[i].Sno + ” + data[i].Name + ” + data[i].Nature + ” + data[i].AnimalCr + ” + data[i].Kismat + ” + data[i].Extra + ”
    tr += “” + td + “”;

    tr += ” Image”;
    // var ntd = “‘”
    var ntd = “‘”
    tr += “” + ntd + “”;
    }
    }

    Reply
  7. this a tr that im appending in above code (Please check var ntd in the code)
    Can src of this image can be bind like this currently it not working
    i can do it by selector but is want like this
    var ntd = “‘”
    tr += “” + ntd + “”;

    Reply
  8. How could I upload the file along with other data using json like:
    $.ajax({
    url: ‘upload.php’,
    type: ‘post’,
    data: {
    data1: …,
    data2: …,
    file: …,
    },
    contentType: json,
    success: function(response){
    if(response != 0){
    $(“#img”).attr(“src”,response);
    $(“.preview img”).show(); // Display image element
    }else{
    alert(‘file not uploaded’);
    }
    },
    });

    Reply
  9. Curious what has to be changed in the code to make it work for video, like MP4. I added that as a valid extension and it doesn’t work. And also wonder why the default image doesn’t show. Doesn’t for me, and doesn’t show in your video. Thanks BTW for the great tutorial.

    Reply
    • Hi Mike,
      You need to specify video file extensions in the $valid_extensions Array. Have you checked php.ini post_max_size and upload_max_filesize values. File will not upload if file size exceed defined max size. You can view this tutorial for reference. Image preview only show if image file successfully uploaded.

      Reply
  10. Hi Yogesh,

    Very nice tutorial and really the easyest in the Internet.
    But how can i achieve that the picture is previewed before i upload it like in your video?
    And cool that you still make suport 2 years later.

    Reply
  11. Thanks very much Mr. Yogesh Singh for the simplified code. What if I want to upload both image file and video file using the same method you used above. Image alone works but uploading with videos returns ‘undefine file index’ errors

    Reply
  12. Oh God I wish i had enough words to thank you brother.Thank you so much.This was what I was looking for the whole time

    Reply
  13. Hi Yogesh,
    Great Tutorial but when I run i get the following error?
    index.html:33 Uncaught ReferenceError: jQuery is not defined
    at index.html:33

    Kind regards
    Jonathan

    Reply
  14. Good Job.
    Question: How to validate this :
    $filename = $_FILES[‘file’][‘name’]; in case not image selected when i click button upload

    Reply
  15. Hello Sir,
    By using the code I am able to upload the file and return the image name(It is showing in the network tab), but could not able to get it in the ajax response. Instead of image name it’s printing some HTML code :(, please help me it’s a bit urgent for me.

    Reply
    • Here are some corrections By using the code I am able to upload the file and return the image name, but Instead of the only image name, it’s printing some HTML code and then showing the image name :(, please help me it’s a bit urgent for me., I have sent you my code with a screenshot in the email.

      Reply

Leave a Comment