Creating jQuery Ajax file upload functionality is pretty confusing for some people as beginners but it can be achieved easily with the following tutorial. Let’s see how to do it step by step. I’m using a simple form with one file input field for this tutorial.

Upload File Using jQuery Ajax

The purpose of this tutorial is to upload files without refreshing the page and even without pressing a submit button. We are going to create a file input field where you can select multiple files and instantly it will be uploaded to your folder and the uploaded files’ names and links to its paths will be listed below.

Essentials for jQuery Ajax file upload

You will need MySQL only when you want to save the upload path.

HTML Markup


<!DOCTYPE html>
<html>
<head>
 <title>void Tricks | Upload file using jquery ajax and php</title>
 <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
</head>
<body>
<div class="wrap">
 <form action="upload.php" method="POST" enctype="multipart/formdata" id="myForm">
 <h1>Upload Files</h1>
 <input type="file" name="myFile" id="myFile" multiple>
 <div id="resultArea"></div>
 <img src="loading.gif" class="loading" width="50" height="auto">
 </form>
</div>
</body>
</html>

We have a form with the id myForm contains a file input field with the id myForm and a result div with the id resultArea and a loading gif.

Don’t forget to include jquery in your page. We are going to use jQuery’s $.ajax method to send POST request to a PHP file where we do stuff to upload the files.

jQuery


$(document).ready(function(){
	$("#myFile").on("change", function(){
		var input = $(this);
		var inputLength = input[0].files.length; //No of files selected
		var file;
		var formData = new FormData();
			for (var i = 0; i < inputLength; i++) {
			file = input[0].files[i];
			formData.append( 'myFile[]', file);
		}
		//send POST request to upload.php
		$.ajax({
			url: "upload.php",
			type: "POST",
			data: formData,
	            	processData: false,
	            	contentType: false,
	            	beforeSend: function(){
	            		$(".loading").show();
	            	}
		}).done(function( data ) {
			$(".loading").hide();
			$("#resultArea").append(data);
			input.val('');
		});
	});
});

Inside of $(document).ready() function we have an on("change") function which will be triggered everytime the files are selected.

Then we have four variables. input is the input field object; inputLength will be the number of files selected; file will be used to store each file object and then finally formData will be used to create datastring to be sent via Ajax request.

Next we need to send a POST request to upload.php. Using beforeSend option we are showing the .loading gif image. By default it should be hidden.

Finally, as usual we are showing the results inside of #resultArea div. Don’t forget to hide the loading image and empty the file input field value.

PHP

This is a pretty basic code for uploading files. I will post another tutorial, if you want an advanced version with more security and more options to validate files by type, size, etc.


<?php
foreach ($_FILES["myFile"]["error"] as $key =&gt; $error) {
 if($error == 0){
 $name = $_FILES["myFile"]["name"][$key];
 $uploadPath = "uploads/" . $name;
 if(move_uploaded_file( $_FILES["myFile"]["tmp_name"][$key], $uploadPath)){
 echo "<a href="&quot;.$uploadPath.&quot;" target="_BLANK">".$name."</a>";
 }
 }
}
?>

Basically, the $_FILES["myFile"] is going to be a multidimentional array. So we are using foreach loop to process each files separately after checking for zero errors.

Create a folder named “uploads” and change its permission to 0777 otherwise files won’t be moved to that folder.

Once a file is successfully moved to the path, we need to echo the name of that file inside an anchor tag linking to the uploaded path of that particular file.

If you want to show the image instead of name of the image simply replace ".$name." to <img src=".$uploadPath." />

PHP with MySQL

If you need to save the paths of the uploaded files into a mysql database, use the following code.


<?php
//change this according to your setup
$link = mysqli_connect("HOST","USERNAME","PASSWORD","DATABASE");

foreach ($_FILES["myFile"]["error"] as $key => $error) {
 if($error == 0){
 $name = $_FILES["myFile"]["name"][$key];
 $uploadPath = "uploads/" . $name;
 if(move_uploaded_file( $_FILES["myFile"]["tmp_name"][$key], $uploadPath)){
 echo "<a href='".$uploadPath."' target='_BLANK'>".$name."</a><br>";
 @mysqli_query($link, "INSERT INTO uploads (path, updated) VALUES ('$uploadPath', NOW())");
 }
 }
}
?>

CSS

Finally, spice it up with some CSS code.


*{
	outline: 0;
}
.wrap{
	width: 500px;
	margin: 40px auto;
}
img{
	max-width: 100%;
}
h1{
	margin-top: 0;
	color: #fff;
	font-size: 24px;
}
#myForm{
	padding: 20px;
	border-radius: 6px;
	background: #707790;
}
#myFile{
	padding: 10px;
	background: #9dc1de;
	width: 96%;
	width: calc(100% - 20px);
	border-radius: 4px;
	border-bottom: 5px solid #cce1f3;
}
.loading{
	display: none;
}
#resultArea{
	margin-top: 15px;
}
#resultArea a{
	color: #99ff94;
	font-size: 16px;
	line-height: 34px;
	border: 1px solid #4d5369;
	padding: 5px 10px;
	border-radius: 4px;
}

That’s it for this jQuery Ajax file upload tutorial.

Checkout How to add more input fields dynamically using jquery.

Finishing Card

The above tutorial is a basic version of ajax file upload. If you need an advanced version let me know in the comment below. Also this code can be used for non multiple input with some little tweak let me know if you need that also.

FYI, the language in the thumbnail is my native language Tamil. I’m using Tamil version of Chrome in case, you were wondering.


Anand Roshan

Author: Anand Roshan

An entrepreneur, programmer and a passionate artist who loves to work independently. Get social: Twitter | Google + | Artist Page

Leave a Reply

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