File upload functionality is a common feature of the dynamic web application. Generally, a form is submitted and the page is refreshed to upload file in PHP. But if you want to provide a better user interface, jQuery and Ajax can be used to upload file without page refresh. In the earlier tutorial, we discussed an easy way to upload files using jQuery and Ajax in PHP. In this tutorial, we will show you the simplest way to upload files or images with form data using jQuery, Ajax, and PHP.
The FormData object compiles a set of key/value pairs to send using XMLHttpRequest. Basically, FormData is used to send the form data via Ajax request same as submit() method. The files can also be sent using FormData by including a file <input> element in the HTML <form>.
This example code will show you how to submit form data and upload file using FormData object and PHP. The following functionality will be implemented in the sample Ajax file upload script.
A table is required to store the form input field’s data and file info 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_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`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. The user can provide their name and email, and select a file 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" name="name" placeholder="Enter name" required />
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" name="email" placeholder="Enter email" required />
</div>
<div class="form-group">
<label for="file">File:</label>
<input type="file" class="form-control" id="file" name="file" required />
</div>
<input type="submit" name="submit" class="btn btn-primary submitBtn" value="SUBMIT"/>
</form>
</div>
JavaScript Code:
The Ajax is used to submit form and file data, so, include the jQuery library first.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
Once the submit button is clicked, the Ajax request is initiated using jQuery.
submit.php
) via Ajax to process upload and data submission.$(document).ready(function(e){
// 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");
}
});
});
});
Validate file type and restrict the user to upload only certain types of file (PDF, MS Word, Image, etc).
this.files
).// File type validation
$("#file").change(function() {
var file = this.files[0];
var fileType = file.type;
var match = ['application/pdf', 'application/msword', 'application/vnd.ms-office', 'image/jpeg', 'image/png', 'image/jpg'];
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;
}
});
This file is loaded by the Ajax request to perform the following operations.
<?php
// File upload folder
$uploadDir = 'uploads/';
// Allowed file types
$allowTypes = array('pdf', 'doc', 'docx', 'jpg', 'png', 'jpeg');
// Default response
$response = array(
'status' => 0,
'message' => 'Form submission failed, please try again.'
);
// If form is submitted
if(isset($_POST['name']) || isset($_POST['email']) || isset($_POST['file'])){
// Get the submitted form data
$name = $_POST['name'];
$email = $_POST['email'];
// Check whether submitted data is not empty
if(!empty($name) && !empty($email)){
// Validate email
if(filter_var($email, FILTER_VALIDATE_EMAIL) === false){
$response['message'] = 'Please enter a valid email.';
}else{
$uploadStatus = 1;
// Upload file
$uploadedFile = '';
if(!empty($_FILES["file"]["name"])){
// File path config
$fileName = basename($_FILES["file"]["name"]);
$targetFilePath = $uploadDir . $fileName;
$fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);
// Allow certain file formats to upload
if(in_array($fileType, $allowTypes)){
// Upload file to the server
if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
$uploadedFile = $fileName;
}else{
$uploadStatus = 0;
$response['message'] = 'Sorry, there was an error uploading your file.';
}
}else{
$uploadStatus = 0;
$response['message'] = 'Sorry, only '.implode('/', $allowTypes).' files are allowed to upload.';
}
}
if($uploadStatus == 1){
// Include the database config file
include_once 'dbConfig.php';
// Insert form data in the database
$sqlQ = "INSERT INTO form_data (name,email,file_name,submitted_on) VALUES (?,?,?,NOW())";
$stmt = $db->prepare($sqlQ);
$stmt->bind_param("sss", $name, $email, $uploadedFile);
$insert = $stmt->execute();
if($insert){
$response['status'] = 1;
$response['message'] = 'Form data submitted successfully!';
}
}
}
}else{
$response['message'] = 'Please fill all the mandatory fields (name and email).';
}
}
// Return response
echo json_encode($response);
Live Image Upload using jQuery, PHP and MySQL
We’ve tried to make the image file upload process simpler and more user-friendly with jQuery and Ajax. You can upload any type of file including image and PDF with the form data without page refresh using jQuery, Ajax, PHP, and MySQL. Use our example code to upload image without page reload using Ajax and PHP. Also, the functionality of the sample Ajax 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
sir, how do you rename files?
Thank you, it’s working.
Thanks
Can we add multiple image upload feature with this ?
Thank you!
Please, how can I add another file field into the code?
can you please help me to add pdf extension
Specify the MIME type (application/pdf) to allow uploading the PDF file.
JavaScript Code:
var match= ["image/jpeg","image/png","image/jpg", "application/pdf"]; if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2]) || (imagefile==match[3]))){ alert('Please select a valid image file (JPEG/JPG/PNG/PDF).'); $("#file").val(''); return false; }
PHP Code:
thx for help me
how can we add more fields in the form and insert them into the database
thanks let me try this out
Can you please make a tutorial of Facebook messenger integration? Thank you
Provide script of two image uploading with data form.
It’s working. thanks a lot.