How to Upload Multiple Images with jQuery AJAX and PHP, with preview

Nakul Kumar · · 7708 Views

Uploading an image without page refresh is more user-friendly than refreshing the entire page. So, in this guide, you will learn how to upload multiple images using ajax in jQuery and PHP. You will also learn how to show the preview of multiple images before uploading them to the server.

Step 1: Create Image Upload Form

Use the following snippet to create an image uploading form.

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

In this snippet, to enable multiple file selection, we have added the multiple attribute and name as an Array type (name='files[]').

And we have also added the <div id='preview'>, here we will display image preview using jQuery before uploading to the server.

Step 2: Script for Ajax request

Next, use the below script that going to make an ajax request to the server to upload images.

<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script>
$(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]);
     		$('#preview').append("<img src='"+URL.createObjectURL(event.target.files[i])+"'>");
       }

       // AJAX request
       $.ajax({
         url: 'ajaxUpload.php', 
         type: 'post',
         data: form_data,
         dataType: 'json',
         contentType: false,
         processData: false,
         success: function (response) {
            alert("Uploaded SuccessFully");
            console.log(response);

         }
       });
    });
});
</script>

In this script, on clicking the upload button, it creates FormData() object, and reads the selected files, and then displays preview images. After that, it makes an ajax request, and we sent the selected images with that ajax.

Step 3: Uploading image in PHP

Create a new file name ajaxUpload.php record and paste the following. In this code, it is going to store the images in the /uploads directory.

<?php
// Count total files
$countfiles = count($_FILES['files']['name']);

// Upload directory
$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;
0

Please login or create new account to add your comment.

0 comments
You may also like:

Exploring the Latest Features in Laravel 11.42: Date Helpers, Validation Upgrades, and More

Laravel continues to evolve with its latest release, version 11.42, bringing a host of developer-friendly features to streamline workflows and enhance code expressiveness. Whether (...)
Harish Kumar

Composition vs. Inheritance in PHP: Why Composition is Better for Your Code

In object-oriented programming, polymorphism can be achieved through two primary approaches: Inheritance and Composition. Let’s dive into their definitions and explore why composition (...)
Harish Kumar

Understanding PHP Invokable Classes: Examples, Use Cases, and Real-World Applications

In PHP, an invokable class is a class you can call like a function. To make a class invokable, PHP provides a special magic method called __invoke(). Once implemented, this allows (...)
Harish Kumar

What is PSR-6? A Beginner’s Guide to PHP Caching Standards

Is your PHP application slowing down because of repeated database queries or inefficient caching? Do you wish switching between caching libraries was simpler? That’s where PSR-6 (...)
Harish Kumar

How to Use useEffect in React: Tips, Examples, and Pitfalls to Avoid

useEffect is one of the most commonly used hooks in React, enabling you to manage side effects like fetching data, subscribing to events, or manipulating the DOM. However, improper (...)
Harish Kumar

15 Must-Know TypeScript Features to Level Up Your Development Skills

TypeScript has become the go-to tool for developers building scalable, maintainable JavaScript applications. Its advanced features go far beyond basic typing, giving developers (...)
Harish Kumar