I have used dropzone.js for uploading multiple files. once uploaded i am getting the reponse from php file and have to update the filename in dropzone so that the file can be deleted immediately. other than that i need to refresh the page and delete the image.
How to achieve it?
This is my code. I am using dropzone.js plugin to add multiple file upload
php file
if (!empty($_FILES)) {
$tempFile = $_FILES['file']['tmp_name'];
$fileName = $_FILES['file']['name'];
$targetPath = APPPATH . 'uploads/work_picture/';
$targetFile = $targetPath . time().$fileName ;
move_uploaded_file($tempFile, $targetFile);
// if you want to save in db,where here
// with out model just for example
// $this->load->database(); // load database
$this->db->insert('tablename',array('business_id'=>$business_id->id,'picture_name' => time().$fileName));
header('Content-type: text/json'); //3
header('Content-type: application/json');
echo json_encode(array("name"=>time().$fileName));
exit;
}
<form action="<?php echo site_url('settings_pro/work_picture_upload'); ?>" class="dropzone dz-clickable" id="my-awesome-dropzone"><div class="dz-default dz-message"><span>Drop Files Here or Click to Upload...</span></div></form>
Dropzone.options.myAwesomeDropzone = {
addRemoveLinks: true ,
maxFiles: 5,
acceptedFiles: 'image/*',
url: "<?php echo site_url('settings_pro/work_picture_upload'); ?>",
init: function() {
thisDropzone = this;
this.on("maxfilesexceeded", function(file){
alert("No more files please!");
this.removeFile(file);
this.addFile(file);
});
this.on('removedfile', function(file) {
console.log(file);
var file_name = file.name;
$.ajax({
type: 'POST',
url: '<?php echo base_url('settings_pro/delete_image'); ?>',
data: { 'filename': file_name },
success: function(report) {
console.log(report);
},
error: function(report) {
console.log(report);
}
});
});
$.get('<?php echo base_url('settings_pro/get_picture'); ?>', function(data) {
$.each(data, function(key,value){
//alert(data);
//var mockFile = { name: value.name, size: value.size };
var mockFile = { name: value.name};
thisDropzone.options.addedfile.call(thisDropzone, mockFile);
thisDropzone.options.thumbnail.call(thisDropzone, mockFile,
value.path);
});
});
this.on("successmultiple", function(files, response) {
alert("hi");
// event when files are successfully uploaded
// you can return a response string and process it here through 'response'
});
this.on("success", function(file, response) {
file.serverId = response;
//$('#dz-preview').html('<img src="" width="200" height="200" alt="<?php //echo $empNameFull; ?>">');
// location.reload();
});
You can try with code might be helpful.
Dropzone.options.myAwesomeDropzone = {
init: function(){
var th = this;
this.on('queuecomplete', function(){
ImageUpload.loadImage(); // CALL IMAGE LOADING HERE
setTimeout(function(){
th.removeAllFiles();
},5000);
})
},
paramName: "file", // The name that will be used to transfer the file
maxFilesize: 2, // MB
acceptedFiles: 'image/*',
};
my.on("complete", function(file) { my.removeFile(file); });
my.on("complete", function(file) { my.removeAllFiles(file);});
Related
its mine upload html code ;
<div class="col-xs-12">
<label for="upload" class="btn btn-sm btn-outline green btn-block">
<i class="fa fa-upload"></i>
upload
</label><input type="file" multiple id="upload" class="hidden"/>
</div>
its file element on change method
$("#upload").change(function (event) {
var files = event.target.files;
files = Object.values(files);
files.forEach(function (file) {
if (file.type.match('image')
|| file.type.match('application/vnd.ms-excel')
|| file.type.match('application/pdf')
|| file.type.match('application/vnd.openxmlformats-officedocument.wordprocessingml.document')
|| file.type.match('application/vnd.openxmlformats-officedocument.presentationml.presentation')
) {
uploadingFile.push(file);
}
});
});
Ajax code when click upload button..
var myFormData = new FormData();
uploadingFile.forEach(function (file) {
myFormData.append('myFiles', file);
});
myFormData.append('a', 1);
$.ajax({
url: 'ajax/upload.php',
type: 'POST',
processData: false, // important
contentType: false, // important
data: myFormData,success: function(data, textStatus, jqXHR)
{
console.log(data);
}
});
And Last of code is php code;
$myFiles=$_FILES["myFiles"];
for($i=0; $i<count($myFiles); $i++){
$target_path = "uploaded_files/";
print_r($myFiles[$i]);
echo $myFiles[$i]["tmp_name"]."\n";
$ext = explode('.',$myFiles[$i]["tmp_name"]);
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1];
$sonuc=move_uploaded_file($myFiles[$i], $target_path);
if(move_uploaded_file($myFiles[$i], $target_path)) {
echo "The file has been uploaded successfully \n";
} else{
echo "There was an error uploading the file, please try again! \n";
}
}
i get this message when run the code. There was an error uploading the file, please try again! I want to upload multiple file to server with array. Why i need an array because I delete some file in array and i want to upload last result of array to server.
What is my fault ? I didn't find anything.
The $myFiles[$i] is a null object.
You are appending single file using this line of code myFormData.append('myFiles', file);. You have to use this code myFormData.append('myFiles[]', file); to send multiple file. Below is the code that i have implemented which can upload multiple files.
in your script place below code.
<script type="text/javascript">
$("#upload").change(function (event) {
var files = event.target.files;
var uploadingFile = [];
files = Object.values(files);
files.forEach(function (file) {
if (file.type.match('image')
|| file.type.match('application/vnd.ms-excel')
|| file.type.match('application/pdf')
|| file.type.match('application/vnd.openxmlformats-officedocument.wordprocessingml.document')
|| file.type.match('application/vnd.openxmlformats-officedocument.presentationml.presentation')
) {
uploadingFile.push(file);
}
});
var myFormData = new FormData();
uploadingFile.forEach(function (file) {
myFormData.append('myFiles[]', file);
});
$.ajax({
url: 'upload.php',
type: 'POST',
processData: false, // important
contentType: false, // important
data: myFormData,success: function(data, textStatus, jqXHR)
{
console.log(data);
}
});
});
</script>
And in your upload php code place below code.
$target_path = "uploaded_files/";
$myFiles=$_FILES["myFiles"];
if(count($myFiles['name']) > 1){
$total = count($myFiles['name']);
for($i=0; $i<$total; $i++){
$ext = explode('.',$myFiles["name"][$i]);
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1];
if(move_uploaded_file($myFiles["tmp_name"][$i], $target_path)) {
echo "The file has been uploaded successfully \n";
} else{
echo "There was an error multiple uploading the file, please try again! \n";
}
}
} else {
$ext = explode('.',$myFiles["name"]);
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1];
if(move_uploaded_file($myFiles["tmp_name"], $target_path)) {
echo "The file has been uploaded successfully \n";
} else{
echo "There was an error uploading the file, please try again! \n";
}
}
try this
$('body').on('click', '#upload', function(e){
e.preventDefault();
var formData = new FormData($(this).parents('form')[0]);
$.ajax({
url: 'upload.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success: function (data) {
alert("Data Uploaded: "+data);
},
data: formData,
cache: false,
contentType: false,
processData: false
});
return false;
});
$("#finalupload").uploadFile({
url: "badocumentsupload",
id: "test",
formData: {
action: 'uploadfile',
_token: tempcsrf,
baid:curaddbaid
},
fileName: "myfile",
returnType: "json",
showDelete: true,
showDone: false,
showProgress: true,
onSuccess: function (files, data, xhr) {
},
deleteCallback: function (data, pd) {
$.post("finaluploaddeletecustom", {
action: "delete_current",
row_id: data['DBID'],
filetodelete: data['uploadedfile'],
_token: tempcsrf
},
function (resp, textStatus, jqXHR) {
reloaddatatable_final();
});
pd.statusbar.hide();//You choice to hide/not.
}
});
As you are getting null object, I don't think that you files are being submitted.I think you have not used enctype="multipart/form-data" in form tag. I think if you add this to form like below, it would work.
<form action="youraction" method="post" enctype="multipart/form-data">
</form>
I have designed a simple form which allows the user to upload files to the server. Initially the form contains one 'browse' button. If the user wants to upload multiple files, he needs to click on the "Add More Files" button which adds another 'browse' button in the form. When the form is submitted, the file upload process is handled in 'upload.php' file. It works perfectly fine for uploading multiple files. Now I need to submit the form by using jQuery's '.submit()' and send a ajax ['.ajax()'] request to the 'upload.php' file to handle the file upload.
Here is my HTML form :
<form enctype="multipart/form-data" action="upload.php" method="post">
<input name="file[]" type="file" />
<button class="add_more">Add More Files</button>
<input type="button" id="upload" value="Upload File" />
</form>
Here is the JavaScript :
$(document).ready(function(){
$('.add_more').click(function(e){
e.preventDefault();
$(this).before("<input name='file[]' type='file' />");
});
});
Here is the code for processing file upload :
for($i=0; $i<count($_FILES['file']['name']); $i++){
$target_path = "uploads/";
$ext = explode('.', basename( $_FILES['file']['name'][$i]));
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1];
if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
echo "The file has been uploaded successfully <br />";
} else{
echo "There was an error uploading the file, please try again! <br />";
}
}
Any suggestions on how I should write my '.submit()' function will be really helpful.
Finally I have found the solution by using the following code:
$('body').on('click', '#upload', function(e){
e.preventDefault();
var formData = new FormData($(this).parents('form')[0]);
$.ajax({
url: 'upload.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success: function (data) {
alert("Data Uploaded: "+data);
},
data: formData,
cache: false,
contentType: false,
processData: false
});
return false;
});
HTML
<form enctype="multipart/form-data" action="upload.php" method="post">
<input name="file[]" type="file" />
<button class="add_more">Add More Files</button>
<input type="button" value="Upload File" id="upload"/>
</form>
Javascript
$(document).ready(function(){
$('.add_more').click(function(e){
e.preventDefault();
$(this).before("<input name='file[]' type='file'/>");
});
});
for ajax upload
$('#upload').click(function() {
var filedata = document.getElementsByName("file"),
formdata = false;
if (window.FormData) {
formdata = new FormData();
}
var i = 0, len = filedata.files.length, img, reader, file;
for (; i < len; i++) {
file = filedata.files[i];
if (window.FileReader) {
reader = new FileReader();
reader.onloadend = function(e) {
showUploadedItem(e.target.result, file.fileName);
};
reader.readAsDataURL(file);
}
if (formdata) {
formdata.append("file", file);
}
}
if (formdata) {
$.ajax({
url: "/path to upload/",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function(res) {
},
error: function(res) {
}
});
}
});
PHP
for($i=0; $i<count($_FILES['file']['name']); $i++){
$target_path = "uploads/";
$ext = explode('.', basename( $_FILES['file']['name'][$i]));
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1];
if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
echo "The file has been uploaded successfully <br />";
} else{
echo "There was an error uploading the file, please try again! <br />";
}
}
/**
Edit: $target_path variable need to be reinitialized and should
be inside for loop to avoid appending previous file name to new one.
*/
Please use the script above script for ajax upload. It will work
Using this source code you can upload multiple file like google one by
one through ajax. Also you can see the uploading progress
HTML
<input type="file" id="multiupload" name="uploadFiledd[]" multiple >
<button type="button" id="upcvr" class="btn btn-primary">Start Upload</button>
<div id="uploadsts"></div>
Javascript
<script>
function uploadajax(ttl,cl){
var fileList = $('#multiupload').prop("files");
$('#prog'+cl).removeClass('loading-prep').addClass('upload-image');
var form_data = "";
form_data = new FormData();
form_data.append("upload_image", fileList[cl]);
var request = $.ajax({
url: "upload.php",
cache: false,
contentType: false,
processData: false,
async: true,
data: form_data,
type: 'POST',
xhr: function() {
var xhr = $.ajaxSettings.xhr();
if(xhr.upload){
xhr.upload.addEventListener('progress', function(event){
var percent = 0;
if (event.lengthComputable) {
percent = Math.ceil(event.loaded / event.total * 100);
}
$('#prog'+cl).text(percent+'%')
}, false);
}
return xhr;
},
success: function (res, status) {
if (status == 'success') {
percent = 0;
$('#prog' + cl).text('');
$('#prog' + cl).text('--Success: ');
if (cl < ttl) {
uploadajax(ttl, cl + 1);
} else {
alert('Done');
}
}
},
fail: function (res) {
alert('Failed');
}
})
}
$('#upcvr').click(function(){
var fileList = $('#multiupload').prop("files");
$('#uploadsts').html('');
var i;
for ( i = 0; i < fileList.length; i++) {
$('#uploadsts').append('<p class="upload-page">'+fileList[i].name+'<span class="loading-prep" id="prog'+i+'"></span></p>');
if(i == fileList.length-1){
uploadajax(fileList.length-1,0);
}
}
});
</script>
PHP
upload.php
move_uploaded_file($_FILES["upload_image"]["tmp_name"],$_FILES["upload_image"]["name"]);
My solution
Assuming that form id = "my_form_id"
It detects the form method and form action from HTML
jQuery code
$('#my_form_id').on('submit', function(e) {
e.preventDefault();
var formData = new FormData($(this)[0]);
var msg_error = 'An error has occured. Please try again later.';
var msg_timeout = 'The server is not responding';
var message = '';
var form = $('#my_form_id');
$.ajax({
data: formData,
async: false,
cache: false,
processData: false,
contentType: false,
url: form.attr('action'),
type: form.attr('method'),
error: function(xhr, status, error) {
if (status==="timeout") {
alert(msg_timeout);
} else {
alert(msg_error);
}
},
success: function(response) {
alert(response);
},
timeout: 7000
});
});
I have upload form that allows users to upload multiple files. I decided that a progress bar would be good if the files are quite large. Below is my source code. I am new to jquery normally I would just php but I find that ajax is more user friendly.
<div id="new_upload">
<div class="close_btn"></div>
<div id="uploads"></div>
<form action="global.func/file_upload.php" method="post" enctype="multipart/form-data" id="upload_file">
<fieldset><legend>Upload an image or video</legend>
<input type="file" id="file" name="file[]" placeholder="Upload Image or Video" multiple /><input type="submit" value="upload file" id="upload_file_btn" required />
</fieldset>
<div class="bar">
<div class="bar_fill" id="pb">
<div class="bar_fill_text" id="pt"></div>
</div>
</div>
</form>
</div>
<script>
function OnProgress(event, position, total, percentComplete){
//Progress bar
console.log(total);
$('#pb').width(percentComplete + '%') //update progressbar percent complete
$('#pt').html(percentComplete + '%'); //update status text
}
function beforeSubmit(){
console.log('ajax start');
}
function afterSuccess(data){
console.log(data);
}
$(document).ready(function(e) {
$('#upload_file').submit(function(event){
event.preventDefault();
var filedata = document.getElementById("file");
formdata = new FormData();
var i = 0, len = filedata.files.length, file;
for (i; i < len; i++) {
file = filedata.files[i];
formdata.append("file[]", file);
}
formdata.append("json",true);
$.ajax({
url: "global.func/file_upload.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
dataType:"JSON",
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
beforeSubmit: beforeSubmit,
uploadProgress:OnProgress,
success: afterSuccess,
resetForm: true
});
});
});
</script>
The image upload works fine, the array send to ajax but the progress bar doesn't move. In fact the console.log for the two functions called need to produce this don't appear either. Is there a correct way to call the functions in my ajax request that would get this progress bar to work.
beforeSubmit: beforeSubmit,
uploadProgress:OnProgress,
success: afterSuccess,
NOTE that this function 'success: afterSuccess' is working as the console is displaying my data.
This is your HTML form
<form method="post" action="uploadImages.php" name ='photo' id='imageuploadform' enctype="multipart/form-data">
<input hidden="true" id="fileupload" type="file" name="image[]" multiple >
<div id ="divleft">
<button id="btnupload"></button>
</div>
</form>
This is your JQuery and ajax.
By default the fileInput is hidden.
Upload Button clicked
$("#btnupload").click(function(e) {
$("#fileupload").click();
e.preventDefault();
});
$('#fileupload').change(function (e) {
$("#imageuploadform").submit();
e.preventDefault();
});
$('#imageuploadform').submit(function(e) {
var formData = new FormData(this);
$.ajax({
type:'POST',
url: 'ajax/uploadImages',
data:formData,
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
myXhr.upload.addEventListener('progress',progress, false);
}
return myXhr;
},
cache:false,
contentType: false,
processData: false,
success:function(data){
console.log(data);
alert('data returned successfully');
},
error: function(data){
console.log(data);
}
});
e.preventDefault();
});
function progress(e){
if(e.lengthComputable){
var max = e.total;
var current = e.loaded;
var Percentage = (current * 100)/max;
console.log(Percentage);
if(Percentage >= 100)
{
// process completed
}
}
}
Your php code looks like this
<?php
header('Content-Type: application/json');
$valid_exts = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
$max_size = 30000 * 1024; // max file size in bytes
$json = array();
if ( $_SERVER['REQUEST_METHOD'] === 'POST' )
{
for($i=0;$i<count($_FILES['image']['tmp_name']);$i++)
{
$path="image/uploads/photos/";
if(is_uploaded_file($_FILES['image']['tmp_name'][$i]) )
{
// get uploaded file extension
$ext = strtolower(pathinfo($_FILES['image']['name'][$i], PATHINFO_EXTENSION));
// looking for format and size validity
if (in_array($ext, $valid_exts) AND $_FILES['image']['size'][$i] < $max_size)
{
// unique file path
$uid = uniqid();
$date = date('Y-m-d-H-i-s');
$path = $path ."image_" .$date. '_' . $uid . "." .$ext;
$returnJson[]= array("filepath"=>$path);
$filename = "image_" . $date . "_" .$uid . "." . $ext;
$this->createthumb($i,$filename);
// move uploaded file from temp to uploads directory
if (move_uploaded_file($_FILES['image']['tmp_name'][$i], $path))
{
//$status = 'Image successfully uploaded!';
//perform sql updates here
}
else {
$status = 'Upload Fail: Unknown error occurred!';
}
}
else {
$status = 'Upload Fail: Unsupported file format or It is too large to upload!';
}
}
else {
$status = 'Upload Fail: File not uploaded!';
}
}
}
else {
$status = 'Bad request!';
}
echo json_encode($json);
?>
You must use a custom XMLHttpRequest to do this with AJAX and jQuery. There's an example here: How can I upload files asynchronously?
I used ajax loader to uplaods files to server.It works fine but now i want to set delete option with each image and can delete that image before saving.My current images look like :
I am using this file uploader script for file uploading.Link
My Code for files upload is :
jQuery("#fileuploader").uploadFile({
url:"<?php echo $this->getUrl('pmembers/priority/productimages/') ?>",
multiple:true,
fileName:"myfile",
onSuccess: function (files, response, xhr,pd) {
var dir = '<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA)."mkd/uploads/".Mage::getSingleton("customer/session")->getId()."/"; ?>';
jQuery('#files').append('<li style="width:60px; float:left;margin-left:5px; margin-right:5px;"><img width="60" height="60" src="'+dir+files+'" /></li><img src="cross.png" />');
},
});
});
Try:
Event when click remove button will send a request to server unlink (path: "dir+files"), after complete server will return client a notify.
jQuery:
var removeButton = $("li > img:last");
removeButton.click(function(){
if (removeButton.attr('handling') != "true") {
removeButton.attr('handling', 'true');
var path = removeButton.prev('img[src]').attr('src');
$.ajax({
type: "POST",
dataType: "json",
url: (url),
data: {'path': path},
error: function () {
//. Action when error.
},
success: function (data) {
//. Action when success.
}
}).done(function(){
removeButton.attr('handling', 'false');
});
}
});
PHP:
$path = $_POST['path'];
$unlink = unlink($path);
if (!$unlink) {
print json_encode(array("return" => false)); exit();
}else {
print json_encode(array("return" => true)); exit();
}
I have designed a simple form which allows the user to upload files to the server. Initially the form contains one 'browse' button. If the user wants to upload multiple files, he needs to click on the "Add More Files" button which adds another 'browse' button in the form. When the form is submitted, the file upload process is handled in 'upload.php' file. It works perfectly fine for uploading multiple files. Now I need to submit the form by using jQuery's '.submit()' and send a ajax ['.ajax()'] request to the 'upload.php' file to handle the file upload.
Here is my HTML form :
<form enctype="multipart/form-data" action="upload.php" method="post">
<input name="file[]" type="file" />
<button class="add_more">Add More Files</button>
<input type="button" id="upload" value="Upload File" />
</form>
Here is the JavaScript :
$(document).ready(function(){
$('.add_more').click(function(e){
e.preventDefault();
$(this).before("<input name='file[]' type='file' />");
});
});
Here is the code for processing file upload :
for($i=0; $i<count($_FILES['file']['name']); $i++){
$target_path = "uploads/";
$ext = explode('.', basename( $_FILES['file']['name'][$i]));
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1];
if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
echo "The file has been uploaded successfully <br />";
} else{
echo "There was an error uploading the file, please try again! <br />";
}
}
Any suggestions on how I should write my '.submit()' function will be really helpful.
Finally I have found the solution by using the following code:
$('body').on('click', '#upload', function(e){
e.preventDefault();
var formData = new FormData($(this).parents('form')[0]);
$.ajax({
url: 'upload.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success: function (data) {
alert("Data Uploaded: "+data);
},
data: formData,
cache: false,
contentType: false,
processData: false
});
return false;
});
HTML
<form enctype="multipart/form-data" action="upload.php" method="post">
<input name="file[]" type="file" />
<button class="add_more">Add More Files</button>
<input type="button" value="Upload File" id="upload"/>
</form>
Javascript
$(document).ready(function(){
$('.add_more').click(function(e){
e.preventDefault();
$(this).before("<input name='file[]' type='file'/>");
});
});
for ajax upload
$('#upload').click(function() {
var filedata = document.getElementsByName("file"),
formdata = false;
if (window.FormData) {
formdata = new FormData();
}
var i = 0, len = filedata.files.length, img, reader, file;
for (; i < len; i++) {
file = filedata.files[i];
if (window.FileReader) {
reader = new FileReader();
reader.onloadend = function(e) {
showUploadedItem(e.target.result, file.fileName);
};
reader.readAsDataURL(file);
}
if (formdata) {
formdata.append("file", file);
}
}
if (formdata) {
$.ajax({
url: "/path to upload/",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function(res) {
},
error: function(res) {
}
});
}
});
PHP
for($i=0; $i<count($_FILES['file']['name']); $i++){
$target_path = "uploads/";
$ext = explode('.', basename( $_FILES['file']['name'][$i]));
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1];
if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
echo "The file has been uploaded successfully <br />";
} else{
echo "There was an error uploading the file, please try again! <br />";
}
}
/**
Edit: $target_path variable need to be reinitialized and should
be inside for loop to avoid appending previous file name to new one.
*/
Please use the script above script for ajax upload. It will work
Using this source code you can upload multiple file like google one by
one through ajax. Also you can see the uploading progress
HTML
<input type="file" id="multiupload" name="uploadFiledd[]" multiple >
<button type="button" id="upcvr" class="btn btn-primary">Start Upload</button>
<div id="uploadsts"></div>
Javascript
<script>
function uploadajax(ttl,cl){
var fileList = $('#multiupload').prop("files");
$('#prog'+cl).removeClass('loading-prep').addClass('upload-image');
var form_data = "";
form_data = new FormData();
form_data.append("upload_image", fileList[cl]);
var request = $.ajax({
url: "upload.php",
cache: false,
contentType: false,
processData: false,
async: true,
data: form_data,
type: 'POST',
xhr: function() {
var xhr = $.ajaxSettings.xhr();
if(xhr.upload){
xhr.upload.addEventListener('progress', function(event){
var percent = 0;
if (event.lengthComputable) {
percent = Math.ceil(event.loaded / event.total * 100);
}
$('#prog'+cl).text(percent+'%')
}, false);
}
return xhr;
},
success: function (res, status) {
if (status == 'success') {
percent = 0;
$('#prog' + cl).text('');
$('#prog' + cl).text('--Success: ');
if (cl < ttl) {
uploadajax(ttl, cl + 1);
} else {
alert('Done');
}
}
},
fail: function (res) {
alert('Failed');
}
})
}
$('#upcvr').click(function(){
var fileList = $('#multiupload').prop("files");
$('#uploadsts').html('');
var i;
for ( i = 0; i < fileList.length; i++) {
$('#uploadsts').append('<p class="upload-page">'+fileList[i].name+'<span class="loading-prep" id="prog'+i+'"></span></p>');
if(i == fileList.length-1){
uploadajax(fileList.length-1,0);
}
}
});
</script>
PHP
upload.php
move_uploaded_file($_FILES["upload_image"]["tmp_name"],$_FILES["upload_image"]["name"]);
My solution
Assuming that form id = "my_form_id"
It detects the form method and form action from HTML
jQuery code
$('#my_form_id').on('submit', function(e) {
e.preventDefault();
var formData = new FormData($(this)[0]);
var msg_error = 'An error has occured. Please try again later.';
var msg_timeout = 'The server is not responding';
var message = '';
var form = $('#my_form_id');
$.ajax({
data: formData,
async: false,
cache: false,
processData: false,
contentType: false,
url: form.attr('action'),
type: form.attr('method'),
error: function(xhr, status, error) {
if (status==="timeout") {
alert(msg_timeout);
} else {
alert(msg_error);
}
},
success: function(response) {
alert(response);
},
timeout: 7000
});
});