Advertisement — Top

Responsive Advertisement

How to insert file and other input type using php and ajax using function

Create Database Table

To store the form input fields and file data, 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_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;

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

File Upload Form with Ajax Request (index.html)

HTML Code:
Initially, an HTML form is displayed with a file input field. The user can provide their name, email, and select a file to upload.
<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">File</label>
<input type="file" class="form-control" id="file" name="file" required />
</div>
<input type="submit" name="submit" class="btn btn-success submitBtn" value="SUBMIT"/>
</form>
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.4.1/jquery.min.js"></script>
Once the submit button is clicked, the Ajax request is initiated using jQuery.
  • The FormData object is used to submit form and file data using Ajax.
  • The form data is sent to the server-side script (submit.php) via Ajax to process upload and data submission.
  • Based on the response, the status is shown on the web page.
$(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){ //console.log(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).
  • On selecting the file, the type is validated using jQuery.
  • Get the type of the selected file using JavaScript File API (this.files).
  • If the file type is not matched with the allowed types, show the alert message.
// 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;
}
});

Upload File and Insert Form Data (submit.php)

This file is loaded by the Ajax request to perform the following functionality.
  • Retrieve the form data using $_POST in PHP.
  • Validate form data to check whether the mandatory fields are empty.
  • Validate email address using FILTER_VALIDATE_EMAIL in PHP.
  • Check the file extension to allow certain file formats (PDF, MS Word, and Image) to upload.
  • Upload file to the server using PHP move_uploaded_file() function.
  • Insert form data and file name in the database.
  • Return response to the Ajax request.
<?php 
$uploadDir 
= 'uploads/'; $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
                
$allowTypes = array('pdf', 'doc', 'docx', 'jpg', 'png', 'jpeg');
                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 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
                
$insert = $db->query("INSERT INTO form_data (name,email,file_name) VALUES ('".$name."','".$email."','".$uploadedFile."')");
                
                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);

Post a Comment

0 Comments