
How to upload file using AJAX and PHP?
Introduction
File can be uploaded using page submit in PHP. Sometimes we need to upload using jQuery and AJAX. This blog post helps to upload file using jquery and AJAX in simplest way. You find step by step process, which helps you to understand in better way.
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
Create index.html file and put following contents into it
<!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
Create a js file, you can name it 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
Create a PHP file, you can name it 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; ?>
Browser compatibility
Chrome | Firefox | IE (Internet Explorer) | Opera | Safari |
---|---|---|---|---|
7.0 | 4.0 | 10 | 12 | 5 |
Conclusion
Simplest way to upload file using jquery and AJAX is FormData object.
We need your support to operate it properly. We have lots of ideas but less fund, so help us with your funding.
A perfection of means, and confusion of aims, seems to be our main problem
Do you want to sell products online with no extra cost?
Send your details, our executive will contact you