Ajax File Upload with Form Data using PHP

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.

  • Submit file with other form data via jQuery Ajax.
  • Upload file to the server and insert form data into the database using PHP and MySQL.

Create Database Table

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;

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 and email, and select a file to upload.

  • Define an element (statusMsg) to display form submission status.
<!-- 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.

  • 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){
                $('.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 operations.

  • 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 
// 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($emailFILTER_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($targetFilePathPATHINFO_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

Conclusion

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

14 Comments

  1. Santi Said...
  2. Ryanid Said...
  3. Mohamed Husein Said...
  4. FADI RIACHI Said...
  5. Jeremiah Succeed Said...
  6. John Oluwaseyi Said...
  7. Djalel Said...
    • CodexWorld Said...
  8. Fayzo Said...
  9. Srijan Said...
  10. Turheeb Said...
  11. Waseemshaz Said...
  12. Pramod Said...
  13. Kangsabati Said...

Leave a reply

keyboard_double_arrow_up