Simply upload file

How to upload file using AJAX and PHP?

Simplest way to upload file is by using FormData. It is used in key/value pairs to send XMLHttpRequest. Initially FormData used to send all form elements data in key/value pair, but it can be used to send keyed data also. Data sent by FormData is in same format as used in form's submit() method. It sends upload data also, if we use multipart/form-data in form's encoding

index.html

<!Doctype HTML>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="main.js"></script>
</head>
<body>
<form name="frmUpdload" id="frmUpdload" method="POST" enctype="multipart/form-data">
	<input type="file" name="txtFile" class="txtFile" />
	<input type="submit" name="btnSubmit" value="Submit" />
</form>
</body>
</html>

main.js

$(document).ready(function() {
	$("form#frmUpdload").submit(function() {
		//Image validation start
		var file_name=$('.txtFile').val();
		var index_dot=file_name.lastIndexOf(".")+1;
		var ext=file_name.substr(index_dot);
		if(file_name=='') {
			alert('Please upload image');
		}
		else if(!(ext=='png' || ext=='jpg' || ext=='jpeg')) {
			alert('Please upload jpg or png image only');
		}	//Image validation end
		else {
			//formdata object to send file upload data
			var formData = new FormData();
			formData.append('fileupload',$( '.txtFile' )[0].files[0], file_name);
			
			$.ajax({
				url: 'upload.php',
				 data: formData,
				 processData: false,
				 contentType: false,
				 type: 'POST',
				 success: function(data){
					alert(data);
				 }
			});
		}
		$('#frmUpdload')[0].reset();
		return false;
	});
});

upload.php

<?php
//print_r($_FILES);	//Check all $_FILES variables
$files=$_FILES['fileupload'];
$tmp_name=$files['tmp_name'];
$name=$files['name'];
$destination=$name;
$res=move_uploaded_file($tmp_name, $destination);
if($res) {
	$msg='Uploaded successfully';
}
else {
	$msg='Error';
}
echo $msg;
?>
Name
Email
Comments
Back
Funding

We need your support to operate it properly. We have lots of ideas but less fund, so help us with your funding.

Thoughts for the day

If a country is to be corruption free and become a nation of beautiful minds, I strongly feel there are three key societal members who can make a difference. They are the father, the mother and the teacher.

Dr. A.P.J. Abdul Kalam
Polls
Which device you use most for facebook application?
Laptop/PC
20%

 


Android
53%

 


IOS
13%

 


Blackberry
14%

 


Tutorial On Request
Q. Ask us for any tutorial or any thing which helps to build your career better.
Email:
Query: