File uploading with ajax and progressbar - php

I am trying to do file upload using ajax and the file is getting upload properly but the problem is i want to show the progress of file upload.
<input type="file" onchange="fileupload(this)" name="song" class="form-control" id="file">
<div id="uploaded_image"><progress id="progress" style="width: 100%;" value="0" max="100"></progress></div>
function fileupload(filee){
var form_data = new FormData();
form_data.append("file", filee.files[0]);
$.ajax({
url:root+"upload.php",
method:"POST",
data: form_data,
contentType: false,
cache: false,
processData: false,
success:function(data)
{
if(data=='valid'){
$('#uploaded_image').html("Ho gyiii");
}else if(data=='not valid'){
$('#uploaded_image').html("nhi Ho gyiii");
}
}
});
}
How set progress value dynamically?
I found this somewhere and it's not working and i am not able to understand this
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
// Upload progress
xhr.upload.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
var percentComplete = (evt.loaded / evt.total)*100;
//Do something with upload progress
console.log(percentComplete);
}
}, false);
// Download progress
xhr.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
// Do something with download progress
alert(percentComplete);
}
}, false);
return xhr;
},
url:root+"upload.php",
method:"POST",
data: form_data,
contentType: false,
cache: false,
processData: false,
success:function(data)
{
if(data=='valid'){
$('#uploaded_image').html("Ho gyiii");
}else if(data=='not valid'){
$('#uploaded_image').html("nhi Ho gyiii");
}
}
});

You can try the below example.
Please replace below values to your values
//your div for showing percent
<div class="progress_bar_in"></div>
//start spinner
$.ajax({
type: type,
url: url,
dataType: dataType,
data: data,
contentType: false,
processData: false,
cache: false,
async: true,
timeout: 60000,
success: function (response) {
//stop spinner
$('.progress_bar_in').html('');
},
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
let percentage = Math.round(percentComplete * 100);
console.log(percentage);
progressBar = `${percentage}`;
if(percentage >= 100){
progressBar = `File reached server and Show some msg till we get response from server`;
}
$('.progress_bar_in').html(progressBar);
}
}, false);
return xhr;
},
error: function (xhr) {
$('.progress_bar_in').html('');
},
});

Related

Ajax Progress bar loading too fast

I am using ajax Progress bar while uploading files to ec2 server. Here uploading works fine. Progress bar loading too fast. It reached 100% before the full file upload.
I refer similar questions but not found the solutions yet.
My code:
function Funname() {
$.ajax({
url: url,
type: 'post',
enctype: 'multipart/form-data',
data: formData,
processData: false, // tell jQuery not to process the data
contentType: false,
dataType: 'json',
success:function(response) {
if(response.success === true) {
$('.progress').hide();
}else {
// error code
}
},
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
$('.progress-bar').width(percentComplete+'%');
$('.progress-bar').html(percentComplete+'%');
}
}, false);
return xhr;
}
});
return false;
}
Where I am doing wrong?

xhr addEventListener not working in framework7

I am trying to add a progressbar with percentage while uploading image in framework7 project. Inside ajax function I am unable to get inside the xhr: function() {. My code is below:
$$.ajax({
url: apiurl,
data: formData,
type: "post",
processData: false,
contentType: false,
dataType:"JSON",
xhr: function() { // iam not getting here
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
console.log(percentComplete);
$('.newprogressbar span').html(Math.round(percentComplete * 100));
}
}, false);
return xhr;
},
success: function(response){
result = JSON.parse(response);
},
error: function(xhr, status){
showweballmessages(lang.networkConnectError,1);
}
});

JQuery fomdata sending empty data to php file?

I am trying to upload file through jquery formdata without any form. My problem is that it is not sending any data to php file.
Here is my jquery code
jQuery(document).ready(function() {
jQuery('#e_picture').change(function() {
var file_data = jQuery('#e_picture').prop('files')[0];
var form_data = new FormData();
form_data.append('e_picture', file_data);
form_data.append('e_uid', '3585');
//});
// data: {e_uid: e_uid, e_picture:'23'},
jQuery.ajax({
url: "index.php?option=com_objectified&task=course_reg.addPicture",
type: 'POST',
data: {
form_data
},
processData: false,
contentType: false,
success: function(result) {
alert('This is ' + result); // Here I show onlu e_uid but it alerts blank result
}
});
});
});
Html
<input type="file" class="form-control" name='e_picture' id='e_picture'>
You are sending the form_data in wrong way
instead of
data: {
form_data
},
just send it like
data: form_data,
jQuery(document).ready(function() {
jQuery('#e_picture').change(function() {
var file_data = jQuery('#e_picture')[0].files;
var form_data = new FormData();
form_data.append("e_picture[]", file_data[0]);
form_data.append('e_uid', '3585');
//});
// data: {e_uid: e_uid, e_picture:'23'},
jQuery.ajax({
url: "index.php?option=com_objectified&task=course_reg.addPicture",
type: 'POST',
data: {
form_data
},
processData: false,
contentType: false,
success: function(result) {
alert('This is ' + result); // Here I show onlu e_uid but it alerts blank result
}
});
});
});
ange content type to :
contentType: 'multipart/form-data',

before submit and uploadProgress doesnt work in ajax jquery

can any one help me in this problem and i try many ways but beforeSubmit and uploadProgrss doesnt work
$.ajax({
url:"include/ajaxPages/admin/insertNewItem.php",
type:"POST",
data:new FormData(this),
processData:false,
contentType:false,
beforeSubmit:function(){
$(this).find(".progress").width("0%");
},
uploadProgress:function(event,position,total,complete){
$(this).find(".progress").animate({
width: complete+"%"
},{
duration:1000
})
},
success:function(data){
console.log(data);
alert("تم الاضافه بنجاح");
$(".loadingViedo").fadeOut();
window.location = document.URL;
}
})
Try this:
var fd = new FormData();
fd.append('rName', $('#upload-resource .upload').attr('data-name'));
fd.append('rfile', $('#upload-resource .upload').attr('data-file'));
$.ajax({
url: 'include/ajaxPages/admin/insertNewItem.php',
data: fd,
processData: false,
contentType: false,
type: 'POST',
xhr: function () { // custom xhr
myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) { // if upload property exists
myXhr.upload.addEventListener('progress', function (e) {
var done = e.position || e.loaded
var total = e.totalSize || e.total;
var percent = Math.round(done / total * 100);
//console.log('xhr progress: ' + percent + '%');
$(this).find(".progress").animate({
width: percent +"%"
},{
duration:1000
});
}, false);
myXhr.addEventListener('load', function (e) {
//upload done
});
$('#upload-resource .cancel').show().click(function () {
//cancel upload
myXhr.abort();
});
}
return myXhr;
},
success: function (data) {
//to do for success result
}
});

access the data passed through FormData on clicking submit button

I have a form with several input fields including file inputs.I am using jquery validate plugin.I need to submit the form using ajax.
HTML:
<form method="post" name="addstudent" id="registrationform" enctype="multipart/form-data">
some fields
<input type="submit" id="buttontext"
class="student_registrationform_button" value="submit" />
Jquery:
$('#buttontext').click(function(){
$("#registrationform").validate({
invalidHandler: function(event, validator) {
//some code
},
submitHandler: function(form){
formdata = false;
if (window.FormData) {
formdata = new FormData();
}
var i = 0, len = $(".file").length, img, reader, file;
$('.file').each(function() { var file = this.files[0];
if (window.FileReader) {
reader = new FileReader();
reader.readAsDataURL(file);
}
if (formdata) {
formdata.append("file", file);
}
});
$.ajax({
url: "process.php",
type: 'POST',
//data: $(this).serialize(),
data: formdata,
cache: false,
contentType: false,
processData: false,
success:function(data){ //alert(data);
console.log(data);return false;
}
Process.php
When I check echo 'action:'.var_dump($_POST); ,its showing null string
(function($) {
$.fn.serializefiles = function() {
var obj = $(this);
var form_data = new FormData(this[0]);
$.each($(obj).find('input[type="file[]"]'), function(i, tag) {
$.each($(tag)[0].files, function(i, file) {
form_data.append(tag.name, file);
});
});
var params = $(obj).serializeArray();
$.each(params, function (i, val) {
form_data.append(val.name, val.value);
});
return form_data;
};
})(jQuery);
var form_id = $('#registrationform');
$.ajax({
type: "POST",
url: "process.php",
data: form_id.serializefiles(),
cache: false,
processData: false,
contentType: false,
success: function (response) {
console.log(data);return false;
}
});
Try this simple function:
submitHandler: function(form){
formdata = new FormData(form);
$.ajax({
url: "process.php",
type: 'POST',
//data: $(this).serialize(),
data: formdata,
cache: false,
contentType: false,
processData: false,
success:function(data){ //alert(data);
console.log(data);return false;
}

Categories