Ajax file upload with form data using php

File upload functionality is a common feature for the dynamic web application. Generally, a khung is submitted and page is refreshed to lớn upload file in PHP. But if you want lớn provide a better user interface, jQuery và Ajax can be used lớn upload file without page refresh. In our earlier tutorial, we have provided an easy way to upload file using jQuery & Ajax in PHP. In this tutorial, we will show you the simplest way to upload file or image with size data using jQuery, Ajax, and PHP.

Bạn đang xem: Ajax file upload with form data using php

The FormData object compiles a phối of key/value pairs to send using XMLHttpRequest. Basically, FormData is used khổng lồ send the khung data same like submit() method. The files can also be sent using FormData by including a file input> element in the HTML form>.

The example code shows how to submit khung data và upload tệp tin using FormData object và PHP. The following functionality will be implemented in the sample Ajax tệp tin upload script.

Submit file with other size data via jQuery Ajax.Upload file to the server and insert khung data into the database using PHP & MySQL.

Create Database Table

To store the form input fields & 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 mặc định CHARSET=utf8 COLLATE=utf8_unicode_ci;

Database Configuration (dbConfig.php)

The dbConfig.php tệp tin is used to connect and select the database using PHP và MySQL. Specify the database host ($dbHost), username ($dbUsername), password ($dbPassword), và name ($dbName) as per your database credentials.

//Databaseconfiguration $dbHost="localhost"; $dbUsername="root"; $dbPassword="root"; $dbName="obatambeienwasirherbal.com"; //Createdatabaseconnection $db=newmysqli($dbHost,$dbUsername,$dbPassword,$dbName); //Checkconnection if($db->connect_error) die("Connectionfailed:".$db->connect_error);

File Upload khung with Ajax Request (index.html)

HTML Code:Initially, an HTML size is displayed with a file input đầu vào field. The user can provide their name, email, & select a file to upload.

Xem thêm: Công Ty Cổ Phần Mềm Dsol Giá Cổ Phiếu Và Biểu Đồ — Otc:Dsol, Phần Mềm Tra Cứu Vòng Bi Skf

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 lớn submit form and file data using Ajax. The form data is sent to lớn 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 khung 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(""+response.message+"

"); else $(".statusMsg").html("

"+response.message+"

"); $("#fupForm").css("opacity",""); $(".submitBtn").removeAttr("disabled"); ); ););

Validate file type và restrict the user khổng lồ upload only certain types of tệp tin (PDF, MS Word, Image, etc).

On selecting the file, the type is validated using jQuery.Get the type of the selected file using JavaScript tệp tin API (this.files).If the tệp tin type is not matched with the allowed types, show the alert message.

// tệp tin type validation$("#file").change(function() (fileType == match<2>) );

Upload File & Insert khung Data (submit.php)

This tệp tin is loaded by the Ajax request to perform the following functionality.

Retrieve the size data using $_POST in PHP
.Validate size data to kiểm tra whether the mandatory fields are empty.Validate email address using FILTER_VALIDATE_EMAIL in PHP.Check the tệp tin extension khổng lồ allow certain file formats (PDF, MS Word, & Image) to upload.Upload file to the vps using PHP move_uploaded_file() function.Insert khung data and file name in the database.Return response to lớn the Ajax request.

="uploads/"; $response=array( "status"=>0, "message"=>"Formsubmissionfailed,pleasetryagain." ); //Ifformissubmitted if(isset($_POST<"name">)||isset($_POST<"email">)||isset($_POST<"file">)) //Getthesubmittedformdata $name=$_POST<"name">; $email=$_POST<"email">; //Checkwhethersubmitteddataisnotempty if(!empty($name)&&!empty($email)) //Validateemail if(filter_var($email,FILTER_VALIDATE_EMAIL)===false) $response<"message">="Pleaseenteravalidemail."; else $uploadStatus=1; //Uploadfile $uploadedFile=""; if(!empty($_FILES<"file"><"name">)) //Filepathconfig $fileName=basename($_FILES<"file"><"name">); $targetFilePath=$uploadDir.$fileName; $fileType=pathinfo($targetFilePath,PATHINFO_EXTENSION); //Allowcertainfileformats $allowTypes=array("pdf","doc","docx","jpg","png","jpeg"); if(in_array($fileType,$allowTypes)) //Uploadfiletotheserver if(move_uploaded_file($_FILES<"file"><"tmp_name">,$targetFilePath)) $uploadedFile=$fileName; else $uploadStatus=0; $response<"message">="Sorry,therewasanerroruploadingyourfile."; else $uploadStatus=0; $response<"message">="Sorry,onlyPDF,DOC,JPG,JPEG,&PNGfilesareallowedtoupload."; if($uploadStatus==1) //Includethedatabaseconfigfile include_once"dbConfig.php"; //Insertformdatainthedatabase $insert=$db->query("INSERTINTOform_data(name,email,file_name)VALUES("".$name."","".$email."","".$uploadedFile."")"); if($insert) $response<"status">=1; $response<"message">="Formdatasubmittedsuccessfully!"; else $response<"message">="Pleasefillallthemandatoryfields(nameandemail)."; //Returnresponse echojson_encode($response);Live Image Upload using jQuery, PHP and MySQL

Conclusion

We’ve tried khổng lồ make the image tệp tin upload process simpler và user-friendly with jQuery và Ajax. You can upload any type of files including image và PDF with the size data without page refresh using jQuery, Ajax, PHP, and MySQL. Use our example code to upload image without page reload using Ajax và PHP. Also, the functionality of the sample Ajax file upload script can be enhanced easily as per your needs.

Are you want to get implementation help, or modify or enhance the functionality of this script? Submit Paid Service Request

If you have any questions about this script, submit it to our QA community - Ask Question