

Upload Multiple Files with Form Data using jQuery, Ajax, and PHP
source link: https://www.codexworld.com/upload-multiple-files-with-form-data-using-jquery-ajax-php/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Upload Multiple Files with Form Data using jQuery, Ajax, and PHP
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.
- Build a web form with multiple images/files attachment.
- Submit the form field’s data without page refresh via Ajax.
- Upload multiple files to the server.
- Insert form data in the database.
Create Database Table
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;
Database Configuration (dbConfig.php)
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);
}
Web Form with Multiple Files Attachment (index.html)
HTML Code:
Initially, an HTML form is displayed with a file input field.
- The file input field allows the user 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:
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.
- On form submit,
- The Ajax request is initiated to send the form data to the server-side.
- The FormData object is used to retrieve the input fields value including files (in key/value pairs).
- The form data is sent to the server-side script (
submit.php
) via Ajax to process the file upload and data submission. - Based on the response, the status is shown on the web page.
- On files select,
- The file type is validated using JavaScript File API (
this.files
). - Allow the user to upload the only certain types of files (Image, PDF, MS Word, etc).
- If the selected file type is not matched with the allowed types, alert message is shown.
- The file type is validated using JavaScript File API (
<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 following code handles the file upload and form submission functionality.
- Retrieve the form fields data using the PHP $_POST method.
- Retrieve the file’s data using the PHP $_FILES method.
- Validate input fields to check whether the mandatory fields are empty.
- Validate email address using FILTER_VALIDATE_EMAIL in PHP.
- Check the files extension to allow certain file formats (Image, PDF, and MS Word) to upload.
- Upload file to the server using PHP move_uploaded_file() function.
- Insert form data and file names in the database.
- Return 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);
Upload Multiple Images using jQuery, Ajax and PHP
Conclusion
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.
Are you want to get implementation help, or modify or enhance the functionality of this script? Submit Paid Service Request
If you have any questions about this script, submit it to our QA community - Ask Question
Recommend
-
8
Home » How To Guides » Ajax » How to Get File Upload Progress in Ajax using jQ...
-
17
Build Popup Contact Form using jQuery and PHP The Contact Form is a must-have feature for the web application. It helps the site admin to get feedback/suggestions/complaints from the users. Generally, the c...
-
6
How to preview image before upload using jQuery - FileReader() Satinder Singh / February 06, 2021 /
-
8
How to disable all input controls inside a form using jQuery 3722 views 1 year ago jQuery ...
-
16
In this tutorial, we are going to learn how to upload single & multiple files and images to the Node server from Vue.js application utilizing Express.js API. Along with that, we will withal learn how to send multipart form data utilizing...
-
13
How to Files Upload with Progress Bar Help of jQuery Ajax & PHP 38344 views 1 year ago PHP
-
8
Multiple Files Upload with Google App Engine Python May 29, 2012...
-
11
Upload Files and Images Using Blueimp jQuery PluginThis is another files and images upload tutorial using jQuery. I am using Blueimp jQuery Plugin to upload files into server folder using JavaScript...
-
9
How to Upload Multiple Files & Images in PHP 7 with MySql Example 10982 views 2 years ago PHP In this tutorial, we will learn...
-
6
How to Upload Multiple Files in an Angular App
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK