Following are simple 4 Steps to upload file asynchronously in PHP.
Step #1
Add jQuery javascript file in your page - Need for Ajax call.
Step #2
Add Following Html, where you want to show the button to upload the file.
Step #3:
Add following javascript code which is responsible for uploading the file.
URL: /folder/upload-file.php
Description: Here you need to write the send the request to server.
$( document ).ready(function() {
$(':button').click(function(){
var formData = new FormData($('form')[0]);
$.ajax({
url: '/folder/upload-file.php', //Location of upload file
type: 'POST',
xhr: function() { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
beforeSend: function(data){},
success: function(data){},
error: function(data){},
data: formData,
cache: false,
contentType: false,
processData: false
});
});
});
Step #4
Add Following code in "/folder/upload-file.php" which will upload the file in Server.
$targetFile="/path/to/upload/file";//Location of srver
if (move_uploaded_file($_FILES["file"]["tmp_name"], $targetFile)) {
echo "success";
} else {
echo "failure";
}
