File upload with form data functionality is very useful for the web form. If you want to allow the user to send an attachment with the web form, file upload functionality needs to be integrated. The form submission and file upload functionality can be implemented easily with PHP. Alternatively, you can build webform with file upload functionality without page refresh using jQuery and Ajax.
JavaScript FormData interface provides an easy way to send form fields and their values to the server-side via Ajax. With the FormData object, the web form submission and file upload functionality can be implemented without page refresh. In this tutorial, we will show you how to upload multiple files with form data using jQuery, Ajax, and PHP.
The following functionality will be implemented in the example Ajax Form with Attachment script.
To store the form data and files info, a table is required in the database. The following SQL creates a form_data
table with some basic fields in the MySQL database.
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;
The dbConfig.php
file is used to connect and select the database using PHP and MySQL. Specify the database host ($dbHost
), username ($dbUsername
), password ($dbPassword
), and name ($dbName
) as per your database credentials.
<?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);
}
HTML Code:
Initially, an HTML form is displayed with a file input field.
<!-- 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 following jQuery code is used to post form data to the server-side script.
submit.php
) via Ajax to process the file upload and data submission.this.files
).<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 following code handles the file upload and form submission functionality.
<?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);
Upload Multiple Images using jQuery, Ajax and PHP
This example code helps you to integrate web form to the website with multiple files upload functionality using jQuery, Ajax, PHP, and MySQL. You can allow the user to upload any type of files including image and PDF with the form data. The form submission handled without page refresh that makes web form user-friendly. The functionality of the Ajax form with multiple file upload script can be enhanced easily as per your needs.
Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request