How to upload Multiple Image files with jQuery AJAX and PHP

Uploading files without refreshing the entire page has become a preferred method in web development as it offers a more user-friendly experience. This approach allows for instant image preview display, enhancing the interaction and engagement with the website or application.

In this tutorial, I will show how to leverage the power of jQuery AJAX and PHP to upload multiple image files and display previews without the need for page refresh. This technique will enhance the functionality and interactivity of your web applications, allowing users to conveniently select and upload multiple images in a smooth and efficient manner.

How to upload Multiple Image files with jQuery AJAX and PHP


Table of Content

  1. HTML: Create file upload layout
  2. jQuery: Setup Multiple File Upload AJAX request
  3. PHP: Handle the Multiple File Upload
  4. Output
  5. Conclusion

1. HTML: Create file upload layout

To create a file upload form:

  • Start with a basic HTML <form>.
  • Add a file input element using <input type="file">.
  • Enable multiple file selection by adding the multiple attribute to the file input.
  • Use the name attribute as an array type by setting it as name='files[]'.
  • Include a button within the form for uploading the selected files.
  • To display image previews using jQuery AJAX after successful upload, utilize a <div> element with the id='preview'.
<style type="text/css">
#preview img{
    margin: 5px;
}
</style>
<form method='post' action='' enctype="multipart/form-data">
    <input type="file" id='files' name="files[]" multiple><br>
    <input type="button" id="submit" value='Upload'>
</form>

<!-- Preview -->
<div id='preview'></div>

2. jQuery: Setup Multiple File Upload AJAX request

  • On the click of the upload button (#submit), create a FormData object.
  • Count the total number of files selected using $('#files')[0].files.length.
  • Loop through the selected files and append them to the form_data object.
  • Send an AJAX POST request to ajaxfile.php, passing form_data as the data.
  • Set the data type as JSON using dataType: 'json'.
  • Set contentType to false and processData to false.
  • In the success callback, loop through the response to get the file paths.
  • Append an <img> element in the <div id='preview'>, using the src variable for the image source.
$(document).ready(function(){

    $('#submit').click(function(){

          var form_data = new FormData();

          // Read selected files
          var totalfiles = document.getElementById('files').files.length;
          for (var index = 0; index < totalfiles; index++) {
               form_data.append("files[]", document.getElementById('files').files[index]);
          }

          // AJAX request
          $.ajax({
               url: 'ajaxfile.php', 
               type: 'post',
               data: form_data,
               dataType: 'json',
               contentType: false,
               processData: false,
               success: function (response) {

                    for(var index = 0; index < response.length; index++) {
                         var src = response[index];

                         // Add img element in <div id='preview'>
                         $('#preview').append('<img src="'+src+'" width="200px;" height="200px">');
                    }

               }
          });

    });

});

3. PHP: Handle the Multiple File Upload

  • Create an ajaxfile.php file and a folder named uploads to store the uploaded files.
  • Count the total number of files received in the request using count($_FILES['files']['name']).
  • Set the upload location to the uploads/ folder.
  • Create an empty array called $files_arr to store the file paths after a successful upload.
  • Loop through each file in the $_FILES.
  • Check if the file name exists and is not empty.
  • Retrieve the file name using $_FILES['files']['name'][$index].
  • Get the file extension using pathinfo($filename, PATHINFO_EXTENSION).
  • Define an array of valid image extensions called $valid_ext.
  • Check if the file extension is in the $valid_ext array.
  • If the extension is valid, construct the file path using the upload location and the file name.
  • Move the file from the temporary location to the specified path using move_uploaded_file().
  • If the file upload is successful, add the file path to the $files_arr array.
  • Encode the $files_arr array into JSON format using json_encode().
  • Return the JSON-encoded $files_arr array to be used for image preview or further processing.
<?php
// Count total files
$countfiles = count($_FILES['files']['name']);

// Upload Location
$upload_location = "uploads/";

// To store uploaded files path
$files_arr = array();

// Loop all files
for($index = 0;$index < $countfiles;$index++){

     if(isset($_FILES['files']['name'][$index]) && $_FILES['files']['name'][$index] != ''){
           // File name
           $filename = $_FILES['files']['name'][$index];

           // Get extension
           $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));

           // Valid image extension
           $valid_ext = array("png","jpeg","jpg");

           // Check extension
           if(in_array($ext, $valid_ext)){

                // File path
                $path = $upload_location.$filename;

                // Upload file
                if(move_uploaded_file($_FILES['files']['tmp_name'][$index],$path)){
                      $files_arr[] = $path;
                }
           }
     }
}

echo json_encode($files_arr);
die;

4. Output

View Output


5. Conclusion

I covered the process of uploading multiple image files using jQuery AJAX and PHP. By following the steps, you learned how to create an HTML form, handle the form submission with jQuery AJAX, and process the uploads on the server using PHP.

You can extend this functionality to support other file types by modifying the code. Enhance your web applications by enabling seamless and efficient multiple image file uploads with jQuery AJAX and PHP.

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