This tutorial is shared for ajax file upload without refreshing the page. You will learn to upload different types of file formats (like jpg, png, gif, pdf, docs, zip, text & more) with some steps that are very simple to understand.

How to Upload File Using jQuery Ajax
Before start coding, you should create the following folder structure.
myproject |__uploads/ |__ajax-script.js |__backend-script.php |__upload-form.php |
Learn Also –
You have to configure the following steps –
1. Create HTML Form
First of all, Configure the following steps to create HTML Form
- Create an HTML form and it must have the following attributes –
method=post– to upload files with security.enctype="multipart/form-data"– It allows us to upload different types of files like images, videos, pdfs, docs, etc.id="uploadFile"– to submit the form using jquery ajax
- Create file upload input field with attribute
type="file" - Also, create a
submitbutton. - Include jQuery CDN to execute ajax script
- Also, Include custom ajax script file
ajax-script.js
File Name – upload-form.php
<!DOCTYPE HTML>
<!DOCTYPE html>
<html>
<head>
<title>AJAX File Upload</title>
</head>
<body>
<form method="post" enctype="multipart/form-data" id="uploadFile">
<input type="file" name="file">
<input type="submit" value="Upload Now" name="submit">
</form>
<div id="alerBox"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript" src="ajax-script.js"></script>
</body>
</html>
2. Write Ajax Script to File Upload
Now, you have to write an ajax script to send a request to the backend script after selecting the file from the local computer.
Configure the following steps to write an ajax script to upload a file
- Apply
submitevent to the form id#uploadFile - Prevent from reloading page using
e.preventDefault()while pressing submit button - Declare formData() object & assign to a variable
formData - Send an ajax request to
backend-script.php - Disable submit button before uploading the file
- Enable submit button and display success message into div
id="alertBox"after uploading the file
File Name – ajax-script.js
$(document).on('submit','#uploadFile',function(e){
e.preventDefault();
var formData = new FormData(this);
$.ajax({
method:"POST",
url: "backend-script.php",
data:formData,
cache:false,
contentType: false,
processData: false,
beforeSend:function(){
$('button[type="submit"]').attr('disabled','disabled');
},
success: function(data){
$('button[type="submit"]').removeAttr('disabled');
$('#alertBox').html(data).fadeIn();
}
});
});
If you want to remove the alert message from the div id="alertBox" after three seconds, you will have to write the following script in backend-script.php file
window.setInterval(function(){
if ($('#alertBox').css("display") == "block") {
$('#alertBox').fadeOut(); }
}, 3000);
3. Write PHP Script to upload File on Ajax Request
Now, create a PHP script to upload the file on an ajax request using the following steps –
- Create a custom function
upload_file() - Declare file upload path & file type in an array and assign them to variables
- Get filename using
$_FILES['file']['name']& temporary file path using$_FILES['name']['name']and assign both to a variable. - Get basename of the selected file using
basename()and assign it to a variable$basename - Concatenate upload file path & basename to make a complete path.
- Get file extension using
pathinfo($originalPath, PATHINFO_EXTENSION) - If the selected file extension is matched with the allowed file extension, upload the file using
move_uploaded_file ($tempPath, $originalPath)otherwise, print an alert message - At last, call created function
upload_file()
File Name – backend-script.php
<?php
upload_file();
function upload_file(){
$uploadTo = "uploads/";
$allowFileType = array('jpg','png','jpeg','gif','pdf','doc');
$fileName = $_FILES['file']['name'];
$tempPath=$_FILES["file"]["tmp_name"];
$basename = basename($fileName);
$originalPath = $uploadTo.$basename;
$fileType = pathinfo($originalPath, PATHINFO_EXTENSION);
if(!empty($fileName)){
if(in_array($fileType, $allowFileType)){
// Upload file to server
if(move_uploaded_file($tempPath,$originalPath)){
echo $fileName." was uploaded successfully";
// write here sql query to store image name in database
}else{
echo 'File Not uploaded ! try again';
}
}else{
echo $fileType." file type not allowed";
}
}else{
echo "Please Select a file";
}
}
?>
Tutorial Summary
I have provided the standard Ajax File Upload Script. I hope, this tutorial will be helpful for you. If you have any doubt or questions, ask me directly through the comment box. I will definitely reply as soon as possible