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` (
 `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,
) 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.

//DB details
$dbHost 'localhost';
$dbUsername 'root';
$dbPassword 'root';
$dbName 'semicolonworld';

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

"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 class="form-group">
      <label for="email">EMAIL</label>
        <input type="email" class="form-control" id="email" name="email" placeholder="Enter email" required />
    <div class="form-group">
        <label for="file">File</label>
        <input type="file" class="form-control" id="file" name="file" required />
    <input type="submit" name="submit" class="btn btn-danger submitBtn" value="SAVE"/>

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.

    $("#fupForm").on('submit', function(e){
            type: 'POST',
            url: 'submit.php',
            data: new FormData(this),
            contentType: false,
            cache: false,
            beforeSend: function(){
            success: function(msg){
                if(msg == 'ok'){
                    $('.statusMsg').html('<span style="font-size:18px;color:#34A853">Form data submitted successfully.</span>');
                    $('.statusMsg').html('<span style="font-size:18px;color:#EA4335">Some problem occurred, please try again.</span>');
    //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).');
            return false;

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.
if(!empty($_POST['name']) || !empty($_POST['email']) || !empty($_FILES['file']['name'])){
$uploadedFile '';
$fileName time().'_'.$_FILES['file']['name'];
$valid_extensions = array("jpeg""jpg""png");
$temporary explode("."$_FILES["file"]["name"]);
$file_extension end($temporary);
$_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;
$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."')");

Related Articles

Comments 0