A Step-by-Step Guide to File Upload with PHP AJAX and jQuery

Uploading the files to a server is a common task in web development.

In PHP you can easily upload any type of file on the server using the move_uploaded_file() method. But it requires a form to be submitted for uploading the selected file.

You can make this process smoother with jQuery AJAX, it also improves user experience. You can directly display the image or file preview after it is been uploaded or alert an error if file is not validated without reloading the page.

For this FormData object is use to pass the selected file to the server using AJAX.

In this tutorial, you’ll learn step-by-step how to use PHP jQuery, and AJAX to upload files with validation and display its preview.

A Step-by-Step Guide to File Upload with PHP AJAX and jQuery


Table of Content

  1. Create an HTML Form for File Uploads
  2. Define the Upload PHP Script
  3. Add jQuery and Ajax to Handle File Uploads
  4. Output
  5. Conclusion

1. Create an HTML Form for File Uploads

Create file element and a button. For file preview create <img > and <a > element. Element gets show/hide for preview after file successfully upload using jQuery.

Completed Code

<div >

     <div >
          <input type="file" id="file" name="file" />
          <input type="button" class="button" value="Upload" id="but_upload">
     </div>

     <!-- File Preview -->
     <div style="margin-top: 40px;" >

          <!-- Image -->
          <img src="" class="prevel" id="imgprev" width="300" style="display: none;" >

          <!-- Non-image -->
          <a href="#" target="_blank" class="prevel" id="fileprev" style="display: none;">View File</a>
     </div>

</div>

2. Define the Upload PHP Script

Create an upload.php file and upload folder to store image files.

Read file extension, initialized $allowed_extensions Array with allowed file extensions – “jpg”,”jpeg”,”png”,”pdf”,”docx”.

Check if file extension exists in $allowed_extensions Array or not. If exists then assign 1 to $status, file location to $response['path'] variable, and extension to $response['extension'].

Return $response Array in JSON format.

Completed Code

<?php

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

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

      /* Location */
      $location = "upload/".$filename;

      /* Extension */
      $extension = pathinfo($location,PATHINFO_EXTENSION);
      $extension = strtolower($extension);

      /* Allowed file extensions */
      $allowed_extensions = array("jpg","jpeg","png","pdf","docx");

      $response = array();
      $status = 0;

      /* Check file extension */
      if(in_array(strtolower($extension), $allowed_extensions)) {

           /* Upload file */
           if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){

                 $status = 1; 
                 $response['path'] = $location;
                 $response['extension'] = $extension;

           }
      }

      $response['status'] = $status;

      echo json_encode($response);
      exit;
}

echo 0;

3. Add jQuery and Ajax to Handle File Uploads

Now that your HTML form is set up, it’s time to add some jQuery and Ajax code to enable file uploads.

Add click event on the upload button. When it gets clicked then read 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.status is 1 or not. If it is 1 means file is successfully uploaded and display preview.

If file extension is pdf or docx then update <a id="fileprev"> href attribute the file path otherwise update <img id="imgprev"> src attribute.

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,
                    dataType: 'json',
                    contentType: false,
                    processData: false,
                    success:function(response){
                         if(response.status == 1){
                              var extension = response.extension;
                              var path = response.path;
                              
                              $('.prevel').hide();
                              if(extension == 'pdf' || extension == 'docx'){
                                    $("#fileprev").attr("href",path);
                                    $("#fileprev").show();
                              }else{
                                    $("#imgprev").attr("src",path);
                                    $("#imgprev").show();
                              }

                         }else{
                              alert('File not uploaded');
                         }
                    }
               });
          }else{
               alert("Please select a file.");
          }
     });
});

4. Output

View Output


5. Conclusion

By following the above steps you can easily upload image or document file and display its preview after upload. Not required to create <form > when using AJAX for file upload, it will work whether the file element is created inside the <form > or not.

Using FormData object to store the file and pass in the AJAX request to upload it. With this, you can pass also additional information with file like – username, userid, new filename, etc. For this, you need to append it in FormData object similar to file – fd.append('filename','newfilename');.

In the PHP file access the file using $_FILES. If you passed other data then access it using $_POST.

Explore our tutorial on uploading multiple files using jQuery AJAX. Alternatively, check out our guide on uploading a file directly to the database.

For a comprehensive understanding of displaying dynamic progress bar during file uploads, you can also refer to this tutorial.

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

62 thoughts on “A Step-by-Step Guide to File Upload with PHP 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