jQuery's "uploadProgress" not firing in "$.ajax" - javascript

I am new to jQuery and now, I am currently working on file uploads. And I want to add some progress bar each time I upload image. I used the uploadProgress in jQuery but it seems doesn't work. Here's my code:
$('#_form_').on('submit', function(e){
var file_and_desc = new FormData($(this)[0]),
form_url = "_pages/_form_";
var ext = choose.val(),
allowed = ['jpg','png'];
if(ext){
var get_ext = ext.split('.');
get_ext.reverse();
if($.inArray(get_ext[0].toLowerCase(), allowed) > -1){
//upload image
$.ajax({
url : form_url,
type: 'POST',
data: file_and_desc,
contentType: false,
processData: false,
uploadProgress: function(event, positio, total, percentComplete){
$('h1').html(percentComplete);
},
success: function(data){
// some code here...
}
});
}
}
});
That's it! What should I do?

According to the $.ajax() reference, uploadProgress is not a valid option.
Instead, the xhr option is used instead, which lets you set progress listeners on the XMLHttpRequest that is used by the ajax request.
this answer shows how to do that:
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = (evt.loaded / evt.total) * 100;
//Do something with upload progress here
}
}, false);
return xhr;
},
type: 'POST',
url: "/",
data: {},
success: function(data){
//Do something on success
}
});

Related

How to show progress bar in percentage?

How I can show the progress of my upload on the screen in percents? I would like to show the bar that starts with 0% and output percentage from percentComplete variable. Once upload is completed I would like to see message completed in the progress bar. If anyone can provide some examples I would appreciate that. Thank you.
<div>Select file for upload:
<input type="file" id="fileUpload" name="fileUpload" onChange="fileUpload()"/>
<span id="showBar"></span>
</div>
Here is my JQuery function:
function fileUpload(){
var reader = new FileReader();
var file = fileExist.files[0];
reader.onload = function(e) {
var text = reader.result.split(/\r\n|\n/);
var myForm = new FormData(document.getElementById('myForm'));
$.ajax({
/*Start-Progress Bar 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);
console.log(percentComplete);
if(percentComplete === 100){
console.log("Successfully uploaded!");
}
}
},false);
return xhr;
},
/*End*/
type: 'POST',
url: 'FileUpload.cfc?method=uploadFile',
data: new FormData($('#myForm')[0]),
cache: false,
contentType: false,
enctype: 'multipart/form-data',
processData: false,
dataType: 'json'
}).done(function(obj){
if(obj.STATUS === 200){
$('#myForm')[0].reset();
}else{
alert('Error!');
}
}).fail(function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
})
}
reader.readAsText(file, 'UTF-8');
}
Have you considered plupload? This is their core example, with simple textual percentage: http://www.plupload.com/examples/core

Avoid multiplication of ajax request

I have a little problem with my functions.
When I execute a function which launchs an Ajax call several times, each time, it multiplicate the number of call.
For example, I want to send a commentary, the first time, all is going good. But if I want to send another, it will be send twice. And if I do it again, it will be send three times.
If you can help me, it will be great :D
Thanks in advance.
Javascript:
$('.modifier').live('click',function(e){
e.preventDefault();
$('#error').hide();
var form = document.querySelector('form')
var formdata = new FormData(form);
formdata.append('fichier', window.file[0]);
//console.log(window.file[0]);
$('input[name=titre]').val('');
$('input[name=fichier]').val('');
$('textarea[name=description]').val('');
window.request_upload = $.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;
$('.chargement').show();
$('.chargement> #progress_bar').css({'width' : percentComplete*100 + '%'}).text(Math.round(percentComplete*100) + '%');
//console.log(percentComplete);
}
}, false);
return xhr;
},
url: "foobar.php",
type: "POST",
data: formdata,
async: true ,
cache: false,
contentType: false,
processData: false
})
.done(function(data){
var json = $.parseJSON(data);
//console.log('Data : '+data);
//console.log('L\'erreur : '+json.erreur);
if(json.erreur == 0)
{
//console.log(json.titre);
var titre = json.titre;
$.notify('Votre photo : "'+titre+'" a bien été envoyé !',{autoHideDelay: 10000, className: 'success'});
$('.drop_depot').removeClass('hover');
$('.chargement').hide();
$(this).removeClass('hover');
$('.drop_depot').empty().append('<span>'+options.message+'</span>');
$('.drop_depot').css({'width': '30%', 'height': '100px' });
$(window).resize();
$('input[type=file]').val('');
}
else{
$('.chargement').hide();
$('#error').show().after(json.erreur + ' ' + json.erreurs);
}
});
}
});
I load this script by : $.getScript() function. If it can help ...
I got the solution.
My problem come from the multiple execution of $.getScript() function.
But I could do this to solve it :
if(!$("body").data(script_bool))
{
$.getScript(script);
$("body").data(script_bool, true);
}
The script_bool variable is the name of the script called.
If it can help someone.

Implement SSE (Server Sent Events) with File Upload to ASHX Handler

I want to implement the following:
Call an ASHX hanlder from UI using Jquery.
Upload a file to this ASHX handler.
And when upload is complete, I want to keep sending messages from the server to UI (SSE) to tell the user about the execution status of the code in ASHX handler.
I am stuck with the 3rd point that has been mentioned above.
Following is the UI code that I have written:
var file = $("input#importFileInputHidden")[0].files[0];
var formData = new FormData();
formData.append('file', file);
importAjaxCall = $.ajax({
xhr: function () {
var xhr = new window.XMLHttpRequest();
$('#progressBar').show();
//Method to show the progress of the file being uploaded
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = Math.round((evt.loaded / evt.total) * 100);
$('#percentageImportComplete').text('' + percentComplete + '%');
$('#importStatus').css('width', percentComplete + '%');
}
}, false);
return xhr;
},
type: 'post',
url: "Handler.ashx",
data: formData,
processData: false,
contentType: false,
success: function (data) {
//Some code to show success status to user
});
How to capture the messages I am sending from the server?
Have to tried to look into responseText property of http request?
success: function () {
console.log(xhr.responseText);
});

Generating a loading bar / percentage when AJAX image upload

I have an image upload feature that works like this:
$('.update-insertimage-form').submit(function() {
$(".submit-newupdate-btn").addClass('disabled');
var rootAsset = $('.rootAsset').html();
var formData = new FormData($('.update-insertimage-form')[0]);
$.ajax({
url: rootAsset+'saveUploadedImage',
type: 'post',
cache: false,
dataType: 'json',
data: formData,
processData: false,
contentType: false,
beforeSend: function() {
$(".form-control-addupdate").append('<div class="uploading-overlay">Uploading Image...</div>');
$(".uploading-overlay").fadeIn();
},
success: function(data) {
$(".submit-newupdate-btn").removeClass('disabled');
if(data.errors) {
$('.modal-body').append('<div class="alert alert-danger centre-text modal-error-message" role="alert"><strong>Error!</strong> '+ data.errors +'</div>');
} else if (data.success) {
$(".form-control-addupdate").append('<img class="temp_added_image" src="/public_html/user_uploads/build_images/'+data.name+'.jpeg"><br><br>');
$(".uploading-overlay").fadeOut(function(){
$(".uploading-overlay").remove();
});
var $t = $('.form-control-addupdate');
$t.animate({"scrollTop": $('.form-control-addupdate')[0].scrollHeight}, "slow");
}
},
error: function(xhr, textStatus, thrownError) {
alert('Something went to wrong.Please Try again later...');
}
});
return false;
});
Instead of just 'Uploading Image' I want to show the user a percentage or a loading bar etc. I have searched around but cannot find much information. My thoughts so far are tracking when the ajax call is made and then when the success call back is returned. But no idea how to generate a loading percentage etc.
I would rather use a percentage number as apposed to a loading bar, and it can be a 'fake' number just so long as it increases and finishes at 100% when the image is uploaded.
Thanks!
EDIT: Just to make it clear, I dont need a specific and real percentage. Just a way of increasing from 1 - 100% from the point the call is made to it being received.
You'll want to include the xhr option in the AJAX request and add an Event Listener to track the progress of the request:
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.addEventListener('progress', function(e) {
$('.progressbar .bar').css('width', '' + (100 * e.loaded / e.total) + '%');
$('.progresspercent').text((100 * e.loaded / e.total) + '%');
});
return xhr;
},
Where progressbar and progresspercent are elements in your HTML

How to send a string along with file via ajax request to a php file?

I got a php file that saves file to server to a folder called upload it receives file via an ajax request every thing works fine so far the next requirement is to send a string along with the file to specify an upload folder & sub folder like "Course/Math" how to achieve that?
JS
$( document ).ready(function() {
$('#Upload').click(function(){
var formData = new FormData($('form')[0]);
$.ajax({
url: 'uploadFile.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
myXhr.upload.addEventListener('progress',progressHandling, false);
}
return myXhr;
},
success: completeHandler,
data: formData,
cache: false,
contentType: false,
processData: false
});
});
var progressHandling = function(e){
if(e.lengthComputable){
var percent = Math.round((e.loaded / e.total) * 100);
$('#uploadprogress').css('width', percent+'%');
}
}
var completeHandler = function(data){
$('#message').text(data);
$('#uploadprogress').css('width', '0%');
$('#file').val('');
};
});
PHP
<?php
if ($_FILES["file"]["error"] > 0) {
} else {
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo true;
}
?>
Sample Example of Sending form data in ajax call with .serialize()
var formData = $('#myform').serialize;
$.ajax({
url: 'uploadFile.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
myXhr.upload.addEventListener('progress',progressHandling, false);
}
return myXhr;
},
success: completeHandler,
data: formData,
cache: false,
contentType: false,
processData: false
});
If you want to add a string simply use like following:
var value = 'test';
var formData = $('#myform').serialize+"&newstring="+value;
Update
File upload is not possible through ajax.
You can upload file, without refreshing page by using IFrame or AjaxFileUpload Plugin.
Further Details here is Answer.
Also file some detail explanation here also:
jQuery Ajax File Upload
jQuery Upload Progress and AJAX file upload
You could use the HTML5 Upload element.
$("#FileUpload").change(function (e) {
var uploadFile = e.target.files;
if (uploadFile.length > 0) {
if (window.FormData !== undefined) {
var data = new FormData();
for (var x = 0; x < uploadFile.length; x++) {
data.append("file" + x, uploadFile[x]);
}
data.append("ELEMENTCLASSNAME", $("#ELEMENTID").val());
$.ajax({
type: "POST",
url: 'URL',
contentType: false,
processData: false,
data: data,
success: function (result) {
alert(result);
},
failure: function (result) {
alert(result);
},
error: function (xhr, status, p3, p4) {
var err = "Error " + " " + status + " " + p3 + " " + p4;
if (xhr.responseText && xhr.responseText[0] == "{")
err = JSON.parse(xhr.responseText).Message;
console.log(err);
}
});
} else {
alert("This browser doesn't support HTML5 file uploads!");
}
}});
On the server side use the Request Object get the value:
var versionName = Request["ELEMENTCLASSNAME"];

Categories