[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:

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

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) {
				console.log(xhr.responseText)
			}
		}</p>
		<p>xhr.open("POST",url, false)
		// Send request to server
		xhr.send(formData)
	}
}

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

<?php
if(isset($_FILES['file']['name'])) {
	print_r($_FILES);
	exit;
}
?>
Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s