AllsWeb Blog
No Result
View All Result
  • Home
  • Main Home
  • PHP and MySQL
  • JavaScript
    • jQuery & AJAX
  • WordPress
  • SEO
  • Web Hosting
  • Comparison
Support
Knowledgebase
  • Home
  • Main Home
  • PHP and MySQL
  • JavaScript
    • jQuery & AJAX
  • WordPress
  • SEO
  • Web Hosting
  • Comparison
No Result
View All Result
AllsWeb White Logo
No Result
View All Result
Home JavaScript jQuery & AJAX

Upload Multiple Images without Page Refresh using jQuery Ajax and PHP

Upload Multiple Images without Page Refresh using jQuery Ajax and PHP

Lakshika Mathur by Lakshika Mathur
December 24, 2019
Reading Time: 5 mins read
0
Upload Multiple Images without Page Refresh using jQuery Ajax and PHP

File or image upload is the maximum used functionality for the web application. Usually, the file upload functionality is useful when you want to permit the user to upload the file to your server. Therefore, you can effortlessly upload a file by using HTML and PHP file input fields. In many cases, the web application permits uploading a single file at a time. But, if you want to help the user to upload multiple files, then uploading all the files at once will provide an exceptional user interface.

RELATED POSTS

What is Application Programming Interface (APIs)?

Like Dislike Rating System with jQuery, Ajax, and PHP

Star Rating System with jQuery, Ajax, PHP, and MySQL

By using PHP, you can upload multiple images at one time. But you may also offer a user-friendly interface to upload multiple images on a single click without page refresh. Therefore, you can upload the image without page reload using Ajax and jQuery. In this tutorial, we will explain to you how to upload multiple images without page refresh using jQuery Ajax and PHP. The sample code shows the Ajax multiple images upload process using jQuery and PHP.

Files Upload Form (index.html)                     

This file handles the process of selecting multiple images, sending Ajax requests.

HTML Code:

Make an HTML form. So, the file input field that permits the user to select multiple files.

  • The <form> tag must contain the  method="post" and  enctype="multipart/form-data" attributes.
  • The <input> tag must contain type="file"  and multiple attributes.
<div class="upload-div">
    <!-- File upload form -->
    <form id="uploadForm" enctype="multipart/form-data">
        <label>Choose Images</label>
        <input type="file" name="images[]" id="fileInput" multiple >
        <input type="submit" name="submit" value="UPLOAD"/>
    </form>
	
    <!-- Display upload status -->
    <div id="uploadStatus"></div>
</div>

Define a DIV element on the web page where you will display the uploaded images in a gallery view.

<!-- Gallery view of uploaded images --> 
<div class="gallery"></div>

SEE ALSO: Upload and Add Watermark to Image using PHP

JavaScript Code:

We have to use the jQuery and Ajax to upload images, include the jQuery library first.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

The jQuery code, which is given below, will send the selected images data to the server-side script via Ajax.

  • Firstly, on form submission, the selected files data is sent to the server-side script (upload.php)  using jQuery and Ajax.
  • Secondly, you have to use the FormData object to retrieve the submitted images data.
  • Based on the response, show the upload status to the user, and the uploaded images are appended to the specified element.
  • At last, the MIME type of the selected files will be validated and restrict the user to upload only the images.
<script>
$(document).ready(function(){
    // File upload via Ajax
    $("#uploadForm").on('submit', function(e){
        e.preventDefault();
        $.ajax({
            type: 'POST',
            url: 'upload.php',
            data: new FormData(this),
            contentType: false,
            cache: false,
            processData:false,
            beforeSend: function(){
                $('#uploadStatus').html('<img src="images/uploading.gif"/>');
            },
            error:function(){
                $('#uploadStatus').html('<span style="color:#EA4335;">Images upload failed, please try again.<span>');
            },
            success: function(data){
                $('#uploadForm')[0].reset();
                $('#uploadStatus').html('<span style="color:#28A74B;">Images uploaded successfully.<span>');
                $('.gallery').html(data);
            }
        });
    });
    
    // File type validation
    $("#fileInput").change(function(){
        var fileLength = this.files.length;
        var match= ["image/jpeg","image/png","image/jpg","image/gif"];
        var i;
        for(i = 0; i < fileLength; i++){ 
            var file = this.files[i];
            var imagefile = file.type;
            if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2]) || (imagefile==match[3]))){
                alert('Please select a valid image file (JPEG/JPG/PNG/GIF).');
                $("#fileInput").val('');
                return false;
            }
        }
    });
});
</script>

Upload Multiple Images using PHP (upload.php)

The upload.php  file is called by the Ajax request to handles the images upload process using PHP.

  • Retrieve the images data from posted data using the PHP $_FILES method.
  • You can use the move_uploaded_file() function in PHP to upload the image in the server.
  • Create an HTML view with the uploaded images.
<?php
if(!empty($_FILES['images'])){
    // File upload configuration
    $targetDir = "uploads/";
    $allowTypes = array('jpg','png','jpeg','gif');
    
    $images_arr = array();
    foreach($_FILES['images']['name'] as $key=>$val){
        $image_name = $_FILES['images']['name'][$key];
        $tmp_name   = $_FILES['images']['tmp_name'][$key];
        $size       = $_FILES['images']['size'][$key];
        $type       = $_FILES['images']['type'][$key];
        $error      = $_FILES['images']['error'][$key];
        
        // File upload path
        $fileName = basename($_FILES['images']['name'][$key]);
        $targetFilePath = $targetDir . $fileName;
        
        // Check whether file type is valid
        $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
        if(in_array($fileType, $allowTypes)){    
            // Store images on the server
            if(move_uploaded_file($_FILES['images']['tmp_name'][$key],$targetFilePath)){
                $images_arr[] = $targetFilePath;
            }
        }
    }
    
    // Generate gallery view of the images
    if(!empty($images_arr)){ ?>
        <ul>
        <?php foreach($images_arr as $image_src){ ?>
            <li><img src="<?php echo $image_src; ?>" alt=""></li>
        <?php } ?>
        </ul>
    <?php }
}
?>

You can show the preview of the selected images without uploading it to the server using PHP.

$images_arr = array();
foreach($_FILES['images']['name'] as $key=>$val){
    $image_name = $_FILES['images']['name'][$key];
    $tmp_name   = $_FILES['images']['tmp_name'][$key];
    $size       = $_FILES['images']['size'][$key];
    $type       = $_FILES['images']['type'][$key];
    $error      = $_FILES['images']['error'][$key];
    
    // File upload path
    $fileName = basename($_FILES['images']['name'][$key]);
    $targetFilePath = $targetDir . $fileName;
    
    // Check whether file type is valid
    $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
    if(in_array($fileType, $allowTypes)){    
        // Display images without storing in the server
        $img_info = getimagesize($_FILES['images']['tmp_name'][$key]);
        $images_arr[] = "data:".$img_info["mime"].";base64,".base64_encode(file_get_contents($_FILES['images']['tmp_name'][$key]));
    }
}

SEE ALSO: Multiple Image Upload with View, Edit and Delete in PHP     

Conclusion

Firstly, we define a simple way to upload multiple images with Ajax and PHP. Secondly, by using our sample code script, you can upload multiple files/images without any jQuery plugin. So, when you want to let the user upload multiple images, the Ajax multiple files upload functionality is beneficial. At last, to make various images upload feature more user-friendly, you can use Drag and drop file upload using Dropzone JS and PHP.

Also, read our previous blog-  Image Gallery CRUD with PHP and MySQL

Tags: jQuery Ajax and PHPMultiple Images
ShareTweetSendShareSharePinScan
Lakshika Mathur

Lakshika Mathur

Related Posts

What is Application Programming Interface (APIs), Types, and Importance.
PHP and MySQL

What is Application Programming Interface (APIs)?

January 29, 2022
61
Like Dislike Rating System with jQuery, Ajax, and PHP
jQuery & AJAX

Like Dislike Rating System with jQuery, Ajax, and PHP

January 6, 2020
739
Star Rating System with jQuery, Ajax, PHP, and MySQL
jQuery & AJAX

Star Rating System with jQuery, Ajax, PHP, and MySQL

January 6, 2020
162
How to Force Download File in PHP
PHP and MySQL

How to Force Download File in PHP

January 2, 2020
82
Form Validation using jQuery Validation Plugin
jQuery & AJAX

Form Validation using jQuery Validation Plugin

January 2, 2020
34
How to Connect to the Remote MySQL Database using PHP
PHP and MySQL

How to Connect to the Remote MySQL Database using PHP

January 1, 2020
28
Next Post
Multiple Image Upload     

Multiple Image Upload with View, Edit and Delete in PHP           

Live Image Upload

Live Image Upload, Crop and Resize using jQuery and PHP

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Categories

  • Comparison (3)
  • HTML & CSS (9)
  • Interesting Facts (1)
  • JavaScript (27)
    • jQuery & AJAX (18)
  • PHP and MySQL (48)
  • Security (10)
  • SEO (2)
  • Trademark (2)
  • Tutorials (5)
  • Uncategorized (1)
  • Web Hosting (19)
    • VPS Server (5)
  • WordPress (8)

Recent Posts

  • Is the Trademark valuable to your Brand or domain?
  • Ideas For Ten Fantastic Online Business From Home
  • Some best free WordPress Themes for Affiliate Marketing Websites
  • Home
  • Posts
  • Privacy Policy
  • Terms and Conditions

Built and Maintained With ♥ by AllsWeb Team

No Result
View All Result
  • Home
  • Main Home
  • PHP and MySQL
  • JavaScript
    • jQuery & AJAX
  • WordPress
  • SEO
  • Web Hosting
  • Comparison

Built and Maintained With ♥ by AllsWeb Team

Go to mobile version