How to upload a file without using a form with Ajax

Updated: 28-Feb-2023 / Tags: Javascript Tutorials / Views: 1537 - Author: George

Introduction

Hi everyone.
If you wonder if it's possible to send a file to the server without using a form element
i can say the answer is yes, we can upload a file without using a form, by using an Ajax request with javascript.

In this quick tutorial i am gonna show you how.

Files we need

  • We need an index.html file, to write our html.
  • A script.js file, for our JavaScript code.
  • A script.php file to handle the Ajax request and save the file to the server.
  • And an uploads/ folder so we can store the uploaded files.

The HTML code

Let's start with the index.html file, in which we have a basic html page structure.

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<link rel="stylesheet" href="styles.css">
	<title>Submit a file with AJAX without using a form</title>
</head>
<body>

	<input id="file" type="file">
	<button id="upload">Upload</button>

	<script src="script.js"></script> <!-- Link to the javascript file -->
</body>
</html>
  • In line 11 we have an input element with the type attribute set to "file".
    We also have its id attribute set to "file" so we can reference the input element from the javascript file.
  • Next in line 12 we have a button with an id attribute set to "upload". We are going to target this button from the JavaScript file, to send the selected file, to the php file.
    And as you noticed we don't have a form element.
  • And in line 14 we have a script tag that points to the javascript file.
  • That's all the html we need. Now let's go to the JavaScript file to send the Ajax request.

The JavaScript code

Let's see what we have in the JavaScript file.

let uploadButton = document.querySelector("#upload");
let file = document.querySelector("#file");

uploadButton.onclick = function(){
	let selectedFile = file.files[0];		
	formdata.append('file', selectedFile);

	let http = new XMLHttpRequest();
	http.open('post', "script.php", true);
	// http.setRequestHeader('Content-Type', 'multipart/form-data');
	http.send(formdata);
}		

Javascript code breakdown

Let's explain the above JavaScript code.

  • The first thing that i will do in the file is to target the input field, and the upload button.

    let uploadButton = document.querySelector("#upload");
    let file = document.querySelector("#file");
    		
  • Next i am going to assign an onclick event-listener on the upload button, so every time we click on it, a function will run.

    uploadButton.onclick = function(){
  • Next in line 5, and inside the function i will create an instance of a FormData object and i will store it in the formdata variable. With the FormData object we can easily construct and send key/value pairs, including files, using an AJAX request to the server.

    	let formdata = new FormData()
    	let selectedFile = file.files[0];		
    	formdata.append('file', selectedFile);
    		

    In line 6 i will get the file that we have selected file.files[0], and i will store it in the selectedFile variable.

    In line 7 i use the append() method that the FormData object has, and i will construct a new key/value pair that has a 'file' key, and value the selected file.
    In the php file we will use the 'file' key to access our uploaded file.

  • Next we are going to create an XMLHttpRequest to send the file to the php file.

    	let http = new XMLHttpRequest();
    	http.open('post', "script.php", true);
    	// http.setRequestHeader('Content-Type', 'multipart/form-data');
    	http.send(formdata);
    		

    In line 8 we create a new instance of an XMLHttpRequest object, and store it in the http variable.

    In line 9, we use the open() method to prepare the request.
    The open() method takes three arguments. In the first argument we set the http method, in our case we are using 'post'. In the second argument we define the file path of the php file that will handle the request, which is our script.php file. And the third argument is set to true, which means we send our request asynchronous.

    In line 10 i have included and commented out the setRequestHeader(), only to show you that we don't have to use a 'Content-type' header when we send data to the server using the FormData object. If you do, you will get an error.

    And in line 11 we use the send() method to send the formdata object to the php file.

    And that's it, this is all the code we need to send the file to the server without using a form. But, if you want also the server's response you can add the following code before the open() method.

    	http.onreadystatechange = function(){
    		if(this.readyState == 4 && this.status == 200){
    			let response = this.responseText;
    			console.log(response);
    		};
    	}
    	// The open() method here:
    		

The PHP code

In the php file we are going to catch the Ajax request from the JavaScript file. So let's see what we have here.

<?php
	if (isset($_FILES['file'])) {
	    $uploads_folder = "uploads/";
	    $file_path = $uploads_folder . $_FILES["file"]["name"];
	    move_uploaded_file($_FILES["file"]["tmp_name"], $file_path);
	}
  • In line 2 we check if the $_FILES Superglobal variable has a key named 'file'. Remember this is the key that we added in the FormData object and is associated with the selected file.
  • In line 3 we create a variable named $uploads_folder and we set as value the path to the folder where we save the files.
  • In line 4 we create the full file path. That includes the folder and the file name.
    In example: "uploads/my-file.pdf", or "uploads/my-image.png" if it is an image.
  • And last in line 5, we use the move_uploaded_file() function to move the file from the temp location to the $file_path that we created in line 4.
  • If we want to send back to the javascript file a message, we could echo something like:

    echo "Your file is uploaded successfully";

As you noticed we don't have any file validation in our php script, this is NOT recommended. You always have to validate all file uploads so you don't get into trouble.

Summary

This is how we can upload a file to the server without using a form element.
I hope you like it, and everything is understandable.

Last Words

Thanks for reading, i hope you find the article helpful.
Please leave a comment if you find any error's, so i can update the page with the correct code.

Source code

You can download the source code and use it in any way you like.

Times downloaded: 90

Buy me a coffee

If you like to say thanks, you can buy me a coffee.

Buy me a coffee with paypal