Skip to Content
PHPCODE
ajax multiple file upload form using jquery demo
php code / September 11, 2021

For the online form, file upload with form data functionality is really useful. If you want the user to be able to send an attachment via the online form, you’ll need to include file upload capabilities. PHP makes it simple to integrate form submission and file upload features. 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 sending form fields and values to the server-side through Ajax simple. The FormData object can be used to implement web form submission and file upload features without requiring a page refresh. We’ll show you how to use jQuery, Ajax, and PHP to upload multiple files with form data in this article.

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

Create a web form that accepts numerous images/files as attachments.
Ajax is used to submit data from a form field without requiring a page refresh.
Multiple files can be uploaded to the server.
Data from the form should be entered into the database.

Make a database table.
A table in the database is required to store the form data and file information. In the MySQL database, the following SQL creates a form data table with some 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;

Configuring the Database (dbConfig.php)
Using PHP and MySQL, the dbConfig.php file is used to connect to and select the database. According to your database credentials, specify 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); 
}

Attaching Multiple Files to a Web Form (index.html)
HTML Code: An HTML form with a file input field is presented at first.

The user can upload numerous files using the file input area.

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

To utilise Ajax, include the jQuery library in your JavaScript code.

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

To post form data to the server-side script, use the jQuery code below.

When a form is submitted, an Ajax request is made to transfer the data from the form to the server.
The FormData object is used to obtain the values of input fields (in key/value pairs), including files.
To process the file upload and data submission, the form data is transferred through Ajax to the server-side script (submit.php).
The status is displayed on the web page based on the response.

The file type is checked using JavaScript File API when you pick files (this.files).
Allow just particular sorts of files to be uploaded by the user (Image, PDF, MS Word, etc).
An alert notice appears if the selected file type does not match the permissible types.

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

The file upload and form submission functions are handled by the code below.

Using the PHP $_POST method, get the data from the form fields.
The PHP $_FILES function is used to get the data from a file.
Validate input fields to ensure that mandatory fields are not left blank.
In PHP, use FILTER VALIDATE EMAIL to validate an email address.
Check the file extension to see if you may upload certain file types (Image, PDF, and MS Word).Insert Form Data and Upload Multiple Files (submit.php)
Using the PHP move uploaded file() method, upload a file to the server.
In the database, enter the form data and file names.
Return the Ajax request’s answer.

<?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);

Note :

Using jQuery, Ajax, PHP, and MySQL, this example code shows how to incorporate a web form into a website with multiple file upload functionality. With the form data, you can allow the user to upload any type of material, including images and PDFs. The submission of the form is processed without the need for a page refresh, making the online form user-friendly. The Ajax form with multiple file upload script’s functionality can be simply customised to meet your needs.

 

PHPCODE © 2024