CoderFunda
  • Home
  • About us
    • Contact Us
    • Disclaimer
    • Privacy Policy
    • About us
  • Home
  • Php
  • HTML
  • CSS
  • JavaScript
    • JavaScript
    • Jquery
    • JqueryUI
    • Stock
  • SQL
  • Vue.Js
  • Python
  • Wordpress
  • C++
    • C++
    • C
  • Laravel
    • Laravel
      • Overview
      • Namespaces
      • Middleware
      • Routing
      • Configuration
      • Application Structure
      • Installation
    • Overview
  • DBMS
    • DBMS
      • PL/SQL
      • SQLite
      • MongoDB
      • Cassandra
      • MySQL
      • Oracle
      • CouchDB
      • Neo4j
      • DB2
      • Quiz
    • Overview
  • Entertainment
    • TV Series Update
    • Movie Review
    • Movie Review
  • More
    • Vue. Js
    • Php Question
    • Php Interview Question
    • Laravel Interview Question
    • SQL Interview Question
    • IAS Interview Question
    • PCS Interview Question
    • Technology
    • Other

13 July, 2020

How to insert file and other input type using php and ajax using function

 Programing Coderfunda     July 13, 2020     No comments   

Create Database Table

To store the form input fields and file data, a table is required 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, email, and select a file to upload.
<form id="fupForm" 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="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-success submitBtn" value="SUBMIT"/>
</form>
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.4.1/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){ //console.log(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 functionality.
  • 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 
$uploadDir 
= 'uploads/'; $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($email, FILTER_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($targetFilePath, PATHINFO_EXTENSION);
                
                
// Allow certain file formats
                
$allowTypes = array('pdf', 'doc', 'docx', '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 PDF, DOC, JPG, JPEG, & PNG files are allowed to upload.';
                }
            }
            
            if(
$uploadStatus == 1){
                
// Include the database config file
                
include_once 'dbConfig.php';
                
                
// Insert form data in the database
                
$insert = $db->query("INSERT INTO form_data (name,email,file_name) VALUES ('".$name."','".$email."','".$uploadedFile."')");
                
                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);
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Email ThisBlogThis!Share to XShare to Facebook
Newer Post Older Post Home

0 comments:

Post a Comment

Thanks

Meta

Popular Posts

  • Write API Integrations in Laravel and PHP Projects with Saloon
    Write API Integrations in Laravel and PHP Projects with Saloon Saloon  is a Laravel/PHP package that allows you to write your API integratio...
  • Features CodeIgniter
    Features CodeIgniter There is a great demand for the CodeIgniter framework in PHP developers because of its features and multiple advan...
  • Laravel Breeze with PrimeVue v4
    This is an follow up to my previous post about a "starter kit" I created with Laravel and PrimeVue components. The project has b...
  • Fast Excel Package for Laravel
      Fast Excel is a Laravel package for importing and exporting spreadsheets. It provides an elegant wrapper around Spout —a PHP package to ...
  • Send message via CANBus
    After some years developing for mobile devices, I've started developing for embedded devices, and I'm finding a new problem now. Th...

Categories

  • Ajax (26)
  • Bootstrap (30)
  • DBMS (42)
  • HTML (12)
  • HTML5 (45)
  • JavaScript (10)
  • Jquery (34)
  • Jquery UI (2)
  • JqueryUI (32)
  • Laravel (1017)
  • Laravel Tutorials (23)
  • Laravel-Question (6)
  • Magento (9)
  • Magento 2 (95)
  • MariaDB (1)
  • MySql Tutorial (2)
  • PHP-Interview-Questions (3)
  • Php Question (13)
  • Python (36)
  • RDBMS (13)
  • SQL Tutorial (79)
  • Vue.js Tutorial (68)
  • Wordpress (150)
  • Wordpress Theme (3)
  • codeigniter (108)
  • oops (4)
  • php (853)

Social Media Links

  • Follow on Twitter
  • Like on Facebook
  • Subscribe on Youtube
  • Follow on Instagram

Pages

  • Home
  • Contact Us
  • Privacy Policy
  • About us

Blog Archive

  • September (100)
  • August (50)
  • July (56)
  • June (46)
  • May (59)
  • April (50)
  • March (60)
  • February (42)
  • January (53)
  • December (58)
  • November (61)
  • October (39)
  • September (36)
  • August (36)
  • July (34)
  • June (34)
  • May (36)
  • April (29)
  • March (82)
  • February (1)
  • January (8)
  • December (14)
  • November (41)
  • October (13)
  • September (5)
  • August (48)
  • July (9)
  • June (6)
  • May (119)
  • April (259)
  • March (122)
  • February (368)
  • January (33)
  • October (2)
  • July (11)
  • June (29)
  • May (25)
  • April (168)
  • March (93)
  • February (60)
  • January (28)
  • December (195)
  • November (24)
  • October (40)
  • September (55)
  • August (6)
  • July (48)
  • May (2)
  • January (2)
  • July (6)
  • June (6)
  • February (17)
  • January (69)
  • December (122)
  • November (56)
  • October (92)
  • September (76)
  • August (6)

Loading...

Laravel News

Loading...

Copyright © CoderFunda | Powered by Blogger
Design by Coderfunda | Blogger Theme by Coderfunda | Distributed By Coderfunda