loading

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

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

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

0 Sales

Free

For the online form, file upload with form data capabilities is really useful. If you want the user to be able to submit a file with the online form, file upload capabilities must be included. PHP makes it simple to add form submission and file upload capability. Alternatively, you may use jQuery and Ajax to create a webform with file upload capability that does not require a page refresh.

 

The JavaScript FormData interface makes it simple to communicate form fields and their data to the server using Ajax. The FormData object may be used to enable online form submission and file upload features without requiring a page refresh. In this article, we'll teach you how to use jQuery, Ajax, and PHP to upload multiple files with form data.

 

In the sample Ajax Form with Attachment script, the following functionality will be implemented.

- Create a web form that accepts numerous images/files as attachments.

- Using Ajax, submit the form field's data without refreshing the page.

- Multiple files should be uploaded to the server.

- Fill in the form data in the database.

 

Create Database Table

 

A table in the database is required to contain the form data and file information. In the MySQL database, the following SQL generates a form data table with the some basic columns.

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)

 

The dbConfig.php script is being used by PHP and MySQL to connect to and choose the database. As per your database credentials, enter the database host ($dbHost), username ($dbUsername), password ($dbPassword), and name ($dbName).

 

<?php 
// Database configuration 
$dbHost     "localhost"; 
$dbUsername "root"; 
$dbPassword "root"; 
$dbName     "codexworld"; 
 
// 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:

Usually, an HTML form with a file input box is presented.

- The file input area allows the user to upload numerous files.

 

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

 

Include the jQuery library to use Ajax.

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

 

The jQuery code below is used to send form data to the server-side script.

 

1. On form submit,

     - An Ajax request is performed to deliver the form data to the server.

     - The FormData type is used to access the values of input fields as well as files (in key/value pairs).

     - Ajax is used to send form data to the server-side script (submit.php) to handle the file upload and data submission.

     - The status is shown on the web page based on the answer.

 

2. On the Files tab,

     - The JavaScript File API is used to validate the file type (this.files).

     - Allow the user to upload just specific file types (Image, PDF, MS Word, etc).

     - If the selected file type does not match one of the permissible kinds, an alert message is displayed.

 

<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 Form Data (submit.php)

 

 

The media upload & form submitting functionality is handled by the code below.

- Using the PHP $_POST method, get the data from the form fields.

- Using the PHP $_FILES method, you may get the file's data.

- Validate input fields to ensure that the essential fields are not left blank.

- In PHP, use FILTER VALIDATE EMAIL to validate an email address.

- Check the file extension to see if specific file types (Image, PDF, and MS Word) may be uploaded.

- Using the PHP move uploaded file() method, upload a file to the server.

- In the database, enter form data and file names.

- Return the result of 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($emailFILTER_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($targetFilePathPATHINFO_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

 

This example code demonstrates how to include a web form into a website with multiple file upload capability by utilising jQuery, Ajax, PHP, and MySQL. You may allow the user to upload any sort of file alongside the form data, including images and PDFs. The form registration is handled without requiring a page refresh, making the online form user-friendly. The features of the Ajax form with multiple file upload script may be simply extended to meet your requirements.

LICENSE OF USE

You can use it for personal or commercial projects. You can't resell it partially or in this form.

PRODUCT INFO

Create Date : Jan 21, 2022

Updated Date : Jan 23, 2022

Ratings

Comments : 0

Downloads : 0