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">

     <!-- 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>


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



      /* 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 */

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


      $response['status'] = $status;

      echo json_encode($response);

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



          var fd = new FormData();

          var files = $('#file')[0].files;

          // Check file selected or not
          if(files.length > 0 ){


                    dataType: 'json',
                    contentType: false,
                    processData: false,
                         if(response.status == 1){
                              var extension = response.extension;
                              var path = response.path;
                              if(extension == 'pdf' || extension == 'docx'){

                              alert('File not uploaded');
               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.