Ajax Progress bar loading too fast - php

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?

Related

File uploading with ajax and progressbar

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('');
},
});

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);
}
});

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
}
});

Php ajax file upload is stopped working in safari

I am using ajax file upload which was working fine before. But suddenly it has stopped working into safari browser.
Here is the code I am using.
$('#addEditCategoryButton').click(function() {
var formData = new FormData($('#editCategoryForm')[0]);
if($("#editCategoryForm").valid()){
var url = window.parent.location.pathname;
var urlPath = url.split("/").pop();
$.ajax({
url: "categories-operations.php",
type: "POST",
data:formData,
contentType: false,
processData: false,
beforeSend: function() {
$("#json-overlay-2").show();
},
success: function(data){
if(data != 'failed') {
if(urlPath != 'manage-categories.php')
{
location.href = 'manage-categories.php';
} else {
table.api().ajax.url( 'categories-operations.php?action=fetchData&catIdUnder=0').load();
$("#addNewEmployeeModal").modal('hide');
}
} else {
$("#installMessage").show();
}
$("#json-overlay-2").hide();
}
});
}
$(document).find("label.error").css('color', 'red');
});
Please help me on this. When I remove contentType: false,processData: false then it works.

jQuery GET request in loop

I have a script that works like this:
when you go to url
localhost/geocinema/index.php?movie=606
it will download the movie number 606 on my server with this script:
$.ajax({
url: link,
type: 'GET',
beforeSend: function() {
console.log("Downloading "+title);
},
complete: function() {
},
success: function(result) {
console.log("Download Success for "+title);
}
});
where the "link" is the php file that handles the download.
now I need to download movies from 1 to 600, so I need to somehow to loop through all that URL-s.
I tried sending get requests from another file, like this:
$.ajax({
url: 'http://localhost/geocinema/index.php?movie={1-600}',
type: 'GET',
beforeSend: function() {
console.log("Downloading ");
},
complete: function() {
},
success: function(result) {
console.log("Download Success ");
}
});
but since I use the get request in index.php also it doesn't work (it doesn't wait until the file is downloaded).
So the only way I can download all files is if I manually enter the URL-s from 1 to 600 in the browser and wait for the download, which is not very convenient.
Any help will be appreciated, thanks.
You might want to create a queue of ajax requests, so each waits until the previous is finished. If you just initiate all ajax request in a for loop, then all of them will fire at the same time. In case we are uploading 600 videos it is going to be a very hard load. So one solution is to use for loop with ajax async flag: false.
for (var i = 1; i <= 600; i++) {
$.ajax({
url: 'http://localhost/geocinema/index.php?movie=' + i,
type: 'GET',
beforeSend: function() {
console.log("Downloading ");
},
async: false,
complete: function() {
},
success: function(result) {
console.log("Download Success ");
}
});
}
Another is do define a function which recursively calls itself when finished uploading.
var currentMovie = 0;
var lastMovie = 600;
function getMovie() {
$.ajax({
url: 'http://localhost/geocinema/index.php?movie='+currentMovie,
type: 'GET',
beforeSend: function() {
console.log("Downloading ");
},
complete: function() {
currentMovie++;
if (currentMoview<=lastMovie) {
getMovie();
}
},
success: function(result) {
console.log("Download Success ");
}
});
}
getMovie();
Use a for loop:
for (var i = 1; i <= 600; i++) {
$.ajax({
url: 'http://localhost/geocinema/index.php?movie=' + i,
type: 'GET',
beforeSend: function() {
console.log("Downloading ");
},
complete: function() {
},
success: function(result) {
console.log("Download Success ");
}
});
}
Do something like this, it will call the same function after completing the previous call
var i = 1;
function ajaxCall(){
$.ajax({
url: 'http://localhost/geocinema/index.php?movie=' + i,
type: 'GET',
beforeSend: function() {
console.log("Downloading ");
},
complete: function() {
},
success: function(result) {
console.log("Download Success ");
if(i++ <= 600){ ajaxCall(); }
}
})
}
ajaxCall();
I solved it like this:
var url = window.location.href;
var ind = url.indexOf("=")+1;
var res = url.substr(ind)
res = parseInt(res);
res = res+1;
var nxurl = "http://localhost/geocinema/index.php?movie="+res;
$.ajax({
url: link,
type: 'GET',
beforeSend: function() {
console.log("Downloading "+title);
},
complete: function() {
},
success: function(result) {
console.log("Download Success for "+title);
window.location = nxurl;
}
});

Categories