A Guide to Upload Multiple Files with Form Data using jQuery, Ajax, and PHP

When you want users to send attachments with web form, then file upload functionality comes into play. You can upload multiple files with form data using jQuery, Ajax, and PHP. In this tutorial, you will learn to enable form submission inside a web form using these languages. 

Further, you can send form fields and its values to the server-side via Ajax using the JavaScript FormData. You can enable web form submission with file upload easily without page refresh. 

So, you are required to follow the below functionality to upload multiple files with form data. You need to implement it in the example Ajax Form with Attachment Script. 

  • Building a web form with multiple Images or file attachment feature
  • Submit the web form field data without refreshing the page via Ajax
  • Upload multiple & various files to the server
  • Insert web form data in the database

Creating Database Table

Firstly, a table is a requisite to put in the web form data & files info in the database. You can implement the following SQL query to create a form_data table with a few basic fields.

CREATE TABLE `form_data` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
 `email` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
 `file_names` varchar(255) COLLATE utf8_unicode_ci NOT NULL COMMENT 'File names in a comma-separated string',
 `submitted_on` datetime NOT NULL DEFAULT current_timestamp(),
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Database Configuration (dbConfig.php)

Secondly, you can connect & select the data in the database using dbConfig.php file. Further, you must state the basic credentials like database host ($dbHost), , username ($dbUsername), password ($dbPassword), and name ($dbName). 

<?php 
// Database configuration 
$dbHost     = "localhost"; 
$dbUsername = "root"; 
$dbPassword = ""; 
$dbName     = "phpsof"; 
 
// Create database connection 
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName); 
 
// Check connection 
if ($db->connect_error) { 
    die("Connection failed: " . $db->connect_error); 
}

Web Form with Multiple Files Attachment (index.html)

HTML Code

In the beginning, an HTML form gets displayed with file input fields. 

  • This field will allow your users to select multiple files to upload. 
<!-- Status message -->
<div class="statusMsg"></div>

<!-- File upload form -->
<div class="col-lg-12">
    <form id="fupForm" enctype="multipart/form-data">
        <div class="form-group">
            <label for="name">Name</label>
            <input type="text" class="form-control" id="name" name="name" placeholder="Enter name" required />
        </div>
        <div class="form-group">
            <label for="email">Email</label>
            <input type="email" class="form-control" id="email" name="email" placeholder="Enter email" required />
        </div>
        <div class="form-group">
            <label for="file">Files</label>
            <input type="file" class="form-control" id="file" name="files[]" multiple />
        </div>
        <input type="submit" name="submit" class="btn btn-success submitBtn" value="SUBMIT"/>
    </form>
</div>

JavaScript Code

Furthermore, Include the following jQuery library to use Ajax. This is the next step to upload multiple files with form data.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  1. On form submit,

  • You need to start the Ajax request to direct the web form data to the server. 
  • You can use the FormData object to fetch the input fields value inclusive of files (in key/value pairs).
  • Thereafter, the form data is sent to server script ( submit.php)to process further. 
  • The status is shown on the website page based on the outcome.
  1. On files select,

  • Your file type is verified using JavaScript File API (this.files)
  • It enables the user to upload Image, PDF, MS Word file, etc. Only certain file types are allowed. 
  • Further, if the file type does not match with the conditions, then the alert message reflects on the screen. 
<script>
$(document).ready(function(){
    // Submit form data via Ajax
    $("#fupForm").on('submit', function(e){
        e.preventDefault();
        $.ajax({
            type: 'POST',
            url: 'submit.php',
            data: new FormData(this),
            dataType: 'json',
            contentType: false,
            cache: false,
            processData:false,
            beforeSend: function(){
                $('.submitBtn').attr("disabled","disabled");
                $('#fupForm').css("opacity",".5");
            },
            success: function(response){
                $('.statusMsg').html('');
                if(response.status == 1){
                    $('#fupForm')[0].reset();
                    $('.statusMsg').html('<p class="alert alert-success">'+response.message+'</p>');
                }else{
                    $('.statusMsg').html('<p class="alert alert-danger">'+response.message+'</p>');
                }
                $('#fupForm').css("opacity","");
                $(".submitBtn").removeAttr("disabled");
            }
        });
    });
	
    // File type validation
    var match = ['application/pdf', 'application/msword', 'application/vnd.ms-office', 'image/jpeg', 'image/png', 'image/jpg'];
    $("#file").change(function() {
        for(i=0;i<this.files.length;i++){
            var file = this.files[i];
            var fileType = file.type;
			
            if(!((fileType == match[0]) || (fileType == match[1]) || (fileType == match[2]) || (fileType == match[3]) || (fileType == match[4]) || (fileType == match[5]))){
                alert('Sorry, only PDF, DOC, JPG, JPEG, & PNG files are allowed to upload.');
                $("#file").val('');
                return false;
            }
        }
    });
});
</script>

Upload Multiple Files and Insert Web Form Data (submit.php)

Moreover, you can use the below code to upload multiple files with form data and enable file submission. 

  • Firstly, fetch the form data using the PHP $_POST method.
  • Secondly, fetch the file data using the PHP $_FILES method.
  • Verify the input fields to fill in the requisite data if any field is found empty.
  • Verify the email through FILTER_VALIDATE_EMAIL in PHP.
  • After that, check the file extensions (Image, PDF, MS Word, etc) to upload it. 
  • Upload files to the server through PHP move_uploaded_file() function. 
  • Insert web form data along with file names in the database.
  • Lastly, initiate response to the Ajax request.
<?php 
$uploadDir = 'uploads/'; 
$allowTypes = array('pdf', 'doc', 'docx', 'jpg', 'png', 'jpeg'); 
$response = array( 
    'status' => 0, 
    'message' => 'Form submission failed, please try again.' 
); 
 
// If form is submitted 
$errMsg = ''; 
$valid = 1; 
if(isset($_POST['name']) || isset($_POST['email']) || isset($_POST['files'])){ 
    // Get the submitted form data 
    $name = $_POST['name']; 
    $email = $_POST['email']; 
    $filesArr = $_FILES["files"]; 
     
    if(empty($name)){ 
        $valid = 0; 
        $errMsg .= '<br/>Please enter your name.'; 
    } 
     
    if(empty($email)){ 
        $valid = 0; 
        $errMsg .= '<br/>Please enter your email.'; 
    } 
     
    if(filter_var($email, FILTER_VALIDATE_EMAIL) === false){ 
        $valid = 0; 
        $errMsg .= '<br/>Please enter a valid email.'; 
    } 
     
    // Check whether submitted data is not empty 
    if($valid == 1){ 
        $uploadStatus = 1; 
        $fileNames = array_filter($filesArr['name']); 
         
        // Upload file 
        $uploadedFile = ''; 
        if(!empty($fileNames)){  
            foreach($filesArr['name'] as $key=>$val){  
                // File upload path  
                $fileName = basename($filesArr['name'][$key]);  
                $targetFilePath = $uploadDir . $fileName;  
                  
                // Check whether file type is valid  
                $fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);  
                if(in_array($fileType, $allowTypes)){  
                    // Upload file to server  
                    if(move_uploaded_file($filesArr["tmp_name"][$key], $targetFilePath)){  
                        $uploadedFile .= $fileName.','; 
                    }else{  
                        $uploadStatus = 0; 
                        $response['message'] = 'Sorry, there was an error uploading your file.'; 
                    }  
                }else{  
                    $uploadStatus = 0; 
                    $response['message'] = 'Sorry, only PDF, DOC, JPG, JPEG, & PNG files are allowed to upload.'; 
                }  
            }  
        } 
         
        if($uploadStatus == 1){ 
            // Include the database config file 
            include_once 'dbConfig.php'; 
             
            // Insert form data in the database 
            $uploadedFileStr = trim($uploadedFile, ','); 
            $insert = $db->query("INSERT INTO form_data (name,email,file_names) VALUES ('".$name."', '".$email."', '".$uploadedFileStr."')"); 
             
            if($insert){ 
                $response['status'] = 1; 
                $response['message'] = 'Form data submitted successfully!'; 
            } 
        } 
    }else{ 
         $response['message'] = 'Please fill all the mandatory fields!'.$errMsg; 
    } 
} 
 
// Return response 
echo json_encode($response);

Conclusion

In conclusion, you can enable the user to upload certain file formats like Image, PDF, etc using this functionality. Moreover, it allows form submission without refreshing the page. So, you can follow this example code to upload multiple files with form data using jQuery, Ajax, and PHP. 

Also Read, A Complete Tutorial to Compress Image before upload using PHP

Stepwise Guide to Add DataTable Custom Filter Dropdown Server-side Processing with PHP