You are on page 1of 9

29/5/2021 Ajax File Upload - Without Refreshing Page - CodingStatus

Home JavaScri pt JQuery React JS Ajax Node.Js PHP Ti ps

SQL Int ervi ew Quest i ons

Ajax Fil e Upl oad – Wit hout Refreshing


Page
March 25, 2021 By Md Nurullah — Leave a Comment

HBO Ahora Más Cerca de Ti


Ad Visita www.hbogola.com y recibe 7

Ad días de prueba gratis


HBO GO Latinoamerica

Probalo Gratis

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.

https://codingstatus.com/ajax-file-upload/ 1/9
29/5/2021 Ajax File Upload - Without Refreshing Page - CodingStatus

Contents [show]

How t o Upl oad Fil e 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 –

Upload File Using PHP

You have to configure the following steps –

https://codingstatus.com/ajax-file-upload/ 2/9
29/5/2021 Ajax File Upload - Without Refreshing Page - CodingStatus

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  submit button.
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 Fil e Upl oad


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 submit event to the form id #uploadFile


https://codingstatus.com/ajax-file-upload/ 3/9
29/5/2021 Ajax File Upload - Without Refreshing Page - CodingStatus

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(); }
https://codingstatus.com/ajax-file-upload/ 4/9
29/5/2021 Ajax File Upload - Without Refreshing Page - CodingStatus
}, 3000);

3. Write PHP Script to upl oad Fil e 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{

https://codingstatus.com/ajax-file-upload/ 5/9
29/5/2021 Ajax File Upload - Without Refreshing Page - CodingStatus
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

Dale Valor a tu Emprendimiento

Permite que los

consumidores que buscan

productos puedan

encontrarlos rápido y
Suscríbase
fácilmente
Stayed Connect

Filed Under: Ajax

Hey there, Welcome to CodingStatus. My Name is Md Nurullah


from Bihar, India. I'm a Software Engineer. I have been working
in the Web Technology field for 3 years. Here, I blog about Web
Development & Designing. Even I help developers to build the
best Web Applications.

Leave a Reply
Your email address will not be published. Required fields are marked *

https://codingstatus.com/ajax-file-upload/ 6/9
29/5/2021 Ajax File Upload - Without Refreshing Page - CodingStatus

Comment

Name *

Email *

Website

Save my name, email, and website in this browser for the next time I
comment.

POST COMMENT

FOLLOW US

  

https://codingstatus.com/ajax-file-upload/ 7/9
29/5/2021 Ajax File Upload - Without Refreshing Page - CodingStatus

RECENT POSTS

React Components – Function and


Class Component
How to Show and Hide Password
Using jQuery
React Fragments
React Js Tutorial
React Render Method – render() |
ReactDOM.render()

INTERVIEW QUESTIONS

HTML Interview Questions


CSS Interview Questions
JavaScript Interview Questions
PHP Interview Questions
SQL Interview Questions

Home About Us Privacy Policy Disclaimer Terms & Conditions Sitemap Contact Us
Copyright © 2021 CodingStatus - All Rights Reserved

https://codingstatus.com/ajax-file-upload/ 8/9
29/5/2021 Ajax File Upload - Without Refreshing Page - CodingStatus

https://codingstatus.com/ajax-file-upload/ 9/9

You might also like