Ajax File Upload with Form Data using PHP

Want to get more information about jquery ajax? Read this article now: Ajax File Upload with Form Data using PHP
jquery ajax

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 element in your the

.

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.

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.

//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.

  

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

  

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.

');                  }else{                      $('.statusMsg').html('Some problem occurred, please try again.');                  }                  $('#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;          }      });  });    Upload File & Insert Form Data (submit.php) 

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

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

Check out the latest information about jquery ajax, azax,azazie and azazel only on uc browser!

RECOMMEND

RELATED SEARCHES