PHP 8 - Ajax File Upload with Form Data using PHP

Last modified: April 03, 2022
1. Create database
  • Either login to phpMyAdmin or mysql workbench
  • In our we are using XAMPP, so follow below steps
  • Start Apache and MySQL services
  • Go to Admin of MySQL

ajax

ajax

create DATABASE demo; CREATE TABLE `Product` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(50) COLLATE utf8_unicode_ci NOT NULL, `file_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
2. Include File
  • Create folder include in C:\xampp\htdocs
  • Create a file called dbconfig.php in include folder
  • Paste the following code, which it is used to database.
<?php $dbHost = "localhost"; $dbUsername = "root"; $dbPassword = ""; $dbName = "demo"; $db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName); if ($db->connect_error) { die("Connection failed: " . $db->connect_error); }
3. Form
  • Create a file name index.php, which is HTML code for the form
  • upload form tha include JQuery CDN links and Ajax Code that call upload.php
<!doctype html> <html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> </head> <body> <form id="uploadForm" 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="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> <script> $(document).ready(function(e){ $("#uploadForm").on('submit', function(e){ e.preventDefault(); $.ajax({ type: 'POST', url: 'upload.php', data: new FormData(this), dataType: 'json', contentType: false, cache: false, processData:false, beforeSend: function(){ $('.submitBtn').attr("disabled","disabled"); }, success: function(response){ console.log(response); $('.message').html(''); if(response.status == 1){ alert(response.message); }else{ alert(response.message); } $(".submitBtn").removeAttr("disabled"); } }); }); }); </script> </body> </html>
3. upload.php
  • Create a file called upload.php in C:\xampp\htdocs
<?php $uploadDir = 'uploads/'; $response = array( 'status' => 0, 'message' => 'Form submission failed, please try again.' ); // If form is submitted if(isset($_POST['name']) || isset($_POST['file'])){ // Get the submitted form data $name = $_POST['name']; // Check whether submitted data is not empty if(!empty($name)){ $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('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 JPG, JPEG, & PNG files are allowed to upload.'; } } if($uploadStatus == 1){ // Include the database config file include_once 'include/dbconfig.php'; // Insert form data in the database $stmt = $db->prepare("INSERT INTO product (name,file_name) VALUES (?, ?)"); $stmt->bind_param("ss", $name, $filename); $name = $name; $filename = $uploadedFile; $insert= $stmt->execute(); $stmt->close(); $db->close(); if($insert){ $response['status'] = 1; $response['message'] = 'Form data submitted successfully!'; } } }else{ $response['message'] = 'Please fill all the mandatory fields (name).'; } } // Return response echo json_encode($response);

Test the application

ajax