[Javascript] Sending files through AJAX

This is a very simple tutorial in which I’ll show you how to send files through AJAX.

First, we need to create our HTML file, with the following content:

	<title>File upload</title>
	<form id="frm_file" method="post">
		<input type="file" name="file" id="file" />
		<button type="button" id="send">Send File</button>
	<script type="text/javascript">

Then, add the following code inside the script tag (If you want, put the code in a js file instead this).

window.onload = function() {
	// Send button
	var button = document.getElementById('send')
	// Get current url
	var url = window.location.toString()
	// Send button onclick listener
	button.onclick = function() {
		// Get form
		var form = document.getElementById('frm_file')
		// Get file input
		var fileInput = document.getElementById('file')
		// Get file object, contains file properties
		var file = fileInput.files[0]</p>
		<p>var formData = new FormData(form)
		// Append the file object to formData
		formData.append("file", file)</p>
		<p>var xhr = new XMLHttpRequest()</p>
		<p>xhr.onreadystatechange = function() {
			// When request is finished,
			// show the response in your browser's console
			if (xhr.readyState == 4) {
		<p>xhr.open("POST",url, false)
		// Send request to server

To see if it’s working, you need to write some code at server-side. You can see an example in php below:

if(isset($_FILES['file']['name'])) {

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s