Ajax File Upload with Form Data using PHP


File upload functionality is the most used feature for the web application. Generally, a form is submitted to upload file in PHP. IF you want to provide a better user interface, jQuery and Ajax can be used to upload file without page refresh. In our earlier tutorial, we have provided the various way to upload file using jQuery and Ajax in PHP. In this tutorial, we will provide the simplest way to upload file or image using 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 same like submit() method. The files can also be sent using FormData by including a file <input> element in your the <form>.

The example code shows 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 image file with other form data using jQuery and Ajax.
  • Upload image and insert form data into the database using PHP and MySQL.

Create Database Table

To store file name and other form data, a table needs to be created 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(100) COLLATE utf8_unicode_ci NOT NULL,
 `email` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
 `file_name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
 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 MySQL database using PHP. Specify the database host ($dbHost), username($dbUsername), password ($dbPassword), and name ($dbName) as per your database credentials.

<?php
//DB details
$dbHost 'localhost';
$dbUsername 'root';
$dbPassword 'root';
$dbName 'codexworld';

//Create connection and select DB
$db = new mysqli($dbHost$dbUsername$dbPassword$dbName);

if(
$db->connect_error){
    die(
"Unable to connect database: " $db->connect_error);
}

Ajax File Upload (index.html)

HTML Code:
Initially, an HTML form will be displayed. The user can provide their name, email, and select an image file to upload.

<p class="statusMsg"></p>
<form enctype="multipart/form-data" id="fupForm" >
    <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-danger submitBtn" value="SAVE"/>
</form>

JavaScript Code:
The jQuery Ajax will be used to submit form data and upload file, include the jQuery library first.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

The FormData object will be used to submit form data with the file using Ajax. Once the form is submitted, the form data will be sent to the PHP file via Ajax for process upload and the status will be shown to the user. Also, the file type will be validated and restrict user upload only the image file.

<script>
$(document).ready(function(e){
    $("#fupForm").on('submit', function(e){
        e.preventDefault();
        $.ajax({
            type: 'POST',
            url: 'submit.php',
            data: new FormData(this),
            contentType: false,
            cache: false,
            processData:false,
            beforeSend: function(){
                $('.submitBtn').attr("disabled","disabled");
                $('#fupForm').css("opacity",".5");
            },
            success: function(msg){
                $('.statusMsg').html('');
                if(msg == 'ok'){
                    $('#fupForm')[0].reset();
                    $('.statusMsg').html('<span style="font-size:18px;color:#34A853">Form data submitted successfully.</span>');
                }else{
                    $('.statusMsg').html('<span style="font-size:18px;color:#EA4335">Some problem occurred, please try again.</span>');
                }
                $('#fupForm').css("opacity","");
                $(".submitBtn").removeAttr("disabled");
            }
        });
    });
    
    //file type validation
    $("#file").change(function() {
        var file = this.files[0];
        var imagefile = file.type;
        var match= ["image/jpeg","image/png","image/jpg"];
        if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2]))){
            alert('Please select a valid image file (JPEG/JPG/PNG).');
            $("#file").val('');
            return false;
        }
    });
});
</script>

Upload File & Insert Form Data (submit.php)

This file is called by the Ajax method and it performs the following functionality.

  • Upload image file to the server (uploads/) using move_uploaded_file() function in PHP.
  • Insert form data in the form_data table of MySQL database.
  • The status will be returned to the success function of Ajax request.
<?php
if(!empty($_POST['name']) || !empty($_POST['email']) || !empty($_FILES['file']['name'])){
    
$uploadedFile '';
    if(!empty(
$_FILES["file"]["type"])){
        
$fileName time().'_'.$_FILES['file']['name'];
        
$valid_extensions = array("jpeg""jpg""png");
        
$temporary explode("."$_FILES["file"]["name"]);
        
$file_extension end($temporary);
        if(((
$_FILES["hard_file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/jpeg")) && in_array($file_extension$valid_extensions)){
            
$sourcePath $_FILES['file']['tmp_name'];
            
$targetPath "uploads/".$fileName;
            if(
move_uploaded_file($sourcePath,$targetPath)){
                
$uploadedFile $fileName;
            }
        }
    }
    
    
$name $_POST['name'];
    
$email $_POST['email'];
    
    
//include database configuration file
    
include_once 'dbConfig.php';
    
    
//insert form data in the database
    
$insert $db->query("INSERT form_data (name,email,file_name) VALUES ('".$name."','".$email."','".$uploadedFile."')");
    
    echo 
$insert?'ok':'err';
}

Conclusion

We’ve tried to make file upload process simpler and user-friendly with jQUery Ajax. Our example code shows how to upload the image without page reload using Ajax and PHP. You can use this script to upload any types of file with Ajax.

Live Image Upload using jQuery, PHP and MySQL

Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request

Recommended Tutorials For You

2 Comments

  1. Pramod Said...
  2. Kangsabati Said...

Leave a reply