· JavaScript · 6 min read
Upload Files without Page Refresh using JavaScript Ajax
JavaScript combined with AJAX provides a powerful way to perform file uploads asynchronously without requiring the page to refresh.
There are few methods to Implement AJAX in JavaScript like – using Fetch API, Axios Library, and using XMLHttpRequest. Here we will explore all these three ways to upload files.
Setup the Project Folder:
To upload files we will use PHP in the backend, so I hope you have PHP development environment. Now, go to your localhost directory (htdocs folder of xampp) and create a new folder called php-ajax-upload
.
Here is the folder structure:
php-ajax-upload/
├── uploads/
├── index.html
└── upload.php
upload.php file is responsible for uploading files to the server. It will move the files into the uploads folder.
Here is the code of this file:
<?php
# upload.php
header('Access-Control-Allow-Origin: *');
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$targetDir = 'uploads/'; // Specify the target directory
$targetFile = $targetDir . basename($_FILES["file"]["name"]); // Get the file name
// Check if file already exists
if (file_exists($targetFile)) {
echo 'Sorry, the file already exists.';
} else {
// Move the uploaded file to the specified directory
if (move_uploaded_file($_FILES['file']['tmp_name'], $targetFile)) {
echo 'File uploaded successfully!';
} else {
echo 'Error uploading file!';
}
}
}
Here is the index.html that includes an input element for file selection, a button to trigger the upload process, and a boiler-plate JS code for uploading files using AJax. The JS ajax code has been omitted as we will add in further steps.
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Ajax File Upload</title>
</head>
<body>
<label for="fileInput">Choose a file:</label>
<input type="file" name="file" id="fileInput" />
<button id="uploadBtn">Upload File</button>
<script>
const uploadBtn = document.getElementById('uploadBtn');
const url = 'http://localhost/php-ajax-upload/upload.php';
uploadBtn.onclick = function (e) {
e.preventDefault();
const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0];
const formData = new FormData();
formData.append('file', file);
// Ajax File Upload Code will Goes Here
};
</script>
</body>
</html>
1. Using Fetch API to upload files:
Fetch API, a modern approach that offer a promise-based interface for making network requests. It supports streaming requests and responses, making it an efficient choice for handling file uploads.
Add this code into the index.html
file:
fetch(url, {
method: 'POST',
body: formData,
})
.then((res) => res.text())
.then((data) => {
alert(data);
})
.catch((error) => {
alert('Error uploading file.');
console.error('Error:', error);
});
2. Using Axios to Upload Files asynchronously:
Axios is a popular HTTP client library that simplifies making HTTP requests in JavaScript. For file uploads, Axios provides a straightforward method akin to Fetch API.
To use axios, first you need to install it or add CDN into the index.html
:
<script src="https://unpkg.com/[email protected]/dist/axios.min.js"></script>
Now you can use axios:
axios
.post(url, formData)
.then((res) => {
alert(res.data);
})
.catch((err) => {
alert(err.message);
console.log(err);
});
Full Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Ajax File Upload</title>
</head>
<body>
<label for="fileInput">Choose a file:</label>
<input type="file" name="file" id="fileInput" />
<button id="uploadBtn">Upload File</button>
<script src="https://unpkg.com/[email protected]/dist/axios.min.js"></script>
<script>
const uploadBtn = document.getElementById('uploadBtn');
const url = 'http://localhost/php-ajax-upload/upload.php';
uploadBtn.onclick = function (e) {
e.preventDefault();
const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0];
const formData = new FormData();
formData.append('file', file);
// Axios
axios
.post(url, formData)
.then((res) => {
alert(res.data);
})
.catch((err) => {
alert(err.message);
console.log(err);
});
};
</script>
</body>
</html>
3. Using XMLHttpRequest:
XMLHttpRequest has long been the workhorse of AJAX requests in JavaScript. It provides a robust, albeit verbose, means of communication with a server.
When it comes to file uploads, XMLHttpRequest requires setting up an instance, defining event listeners for progress tracking, and manually handling the request.
Here is the XMLHttpRequest code for uploading files via ajax:
const xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.onload = function () {
if (xhr.status === 200) {
const responseData = xhr.responseText;
alert(responseData);
} else {
alert('Error uploading file.');
console.error(xhr.status + ' - ' + xhr.statusText);
}
};
xhr.send(formData);
Setup the Project Folder:
To upload files we will use PHP (you can use node, python etc.) in the backend, so I hope you have PHP development environment. Now, go to your localhost directory (htdocs folder of xampp) and create a new folder called php-ajax-upload
.
Here is the folder structure:
php-ajax-upload/
├── uploads/
├── index.html
└── upload.php
upload.php file is responsible for uploading files to the server. It will move the files into the uploads folder.
Here is the code of this file:
<?php
# upload.php
header('Access-Control-Allow-Origin: *');
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$targetDir = 'uploads/'; // Specify the target directory
$targetFile = $targetDir . basename($_FILES["file"]["name"]); // Get the file name
// Check if file already exists
if (file_exists($targetFile)) {
echo 'Sorry, the file already exists.';
} else {
// Move the uploaded file to the specified directory
if (move_uploaded_file($_FILES['file']['tmp_name'], $targetFile)) {
echo 'File uploaded successfully!';
} else {
echo 'Error uploading file!';
}
}
}
Here is the index.html that includes an input element for file selection, a button to trigger the upload process, and a boiler-plate JS code for uploading files using AJax. The JS ajax code has been omitted as we will add in further steps.
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Ajax File Upload</title>
</head>
<body>
<label for="fileInput">Choose a file:</label>
<input type="file" name="file" id="fileInput" />
<button id="uploadBtn">Upload File</button>
<script>
const uploadBtn = document.getElementById('uploadBtn');
const url = 'http://localhost/php-ajax-upload/upload.php';
uploadBtn.onclick = function (e) {
e.preventDefault();
const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0];
const formData = new FormData();
formData.append('file', file);
// Ajax File Upload Code will Goes Here
};
</script>
</body>
</html>
1. Using Fetch API to upload files:
Fetch API, a modern approach that offer a promise-based interface for making network requests. It supports streaming requests and responses, making it an efficient choice for handling file uploads.
Add this code into the index.html
file:
fetch(url, {
method: 'POST',
body: formData,
})
.then((res) => res.text())
.then((data) => {
alert(data);
})
.catch((error) => {
alert('Error uploading file.');
console.error('Error:', error);
});
2. Using Axios to Upload Files asynchronously:
Axios is a popular HTTP client library that simplifies making HTTP requests in JavaScript. For file uploads, Axios provides a straightforward method akin to Fetch API.
To use axios, first you need to install it or add CDN into the index.html
:
<script src="https://unpkg.com/[email protected]/dist/axios.min.js"></script>
Now you can use axios:
axios
.post(url, formData)
.then((res) => {
alert(res.data);
})
.catch((err) => {
alert(err.message);
console.log(err);
});
Full Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Ajax File Upload</title>
</head>
<body>
<label for="fileInput">Choose a file:</label>
<input type="file" name="file" id="fileInput" />
<button id="uploadBtn">Upload File</button>
<script src="https://unpkg.com/[email protected]/dist/axios.min.js"></script>
<script>
const uploadBtn = document.getElementById('uploadBtn');
const url = 'http://localhost/php-ajax-upload/upload.php';
uploadBtn.onclick = function (e) {
e.preventDefault();
const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0];
const formData = new FormData();
formData.append('file', file);
// Axios
axios
.post(url, formData)
.then((res) => {
alert(res.data);
})
.catch((err) => {
alert(err.message);
console.log(err);
});
};
</script>
</body>
</html>
3. Using XMLHttpRequest:
XMLHttpRequest has long been the workhorse of AJAX requests in JavaScript. It provides a robust, albeit verbose, means of communication with a server.
When it comes to file uploads, XMLHttpRequest requires setting up an instance, defining event listeners for progress tracking, and manually handling the request.
Here is the XMLHttpRequest code for uploading files via ajax:
const xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.onload = function () {
if (xhr.status === 200) {
const responseData = xhr.responseText;
alert(responseData);
} else {
alert('Error uploading file.');
console.error(xhr.status + ' - ' + xhr.statusText);
}
};
xhr.send(formData);