Close fancybox at the end of file upload progress - javascript

I have a script to show a progress bar for when a user is uploading images. This upload form is within an open fancybox that I want to have closed once the images are finished uploading.
If I use a onclick event for when the user clicks the submit button to close the fancybox, it will not complete the image upload process.
Here is what I have for the progress bar. I'm wondering if there is a way to close fancybox once the progress bar gives the done message?
<script>
$(document).on('submit', 'form[profile-picture-data-remote]', function(e) {
e.preventDefault();
var fd = new FormData(this);
$.ajax({
url: $(this).attr('action'),
xhr: function() {
var xhr = new XMLHttpRequest();
var total = 0;
$.each(document.getElementById('profile-image-upload').files, function(i, file) {
total += file.size;
});
xhr.upload.addEventListener("progress", function(evt) {
var loaded = (evt.loaded / total).toFixed(2)*100;
$('#progress-container').css({
'display': 'block'
});
$('#progress').text('Uploading... ' + loaded + '%');
$('#progress').css({
'width': loaded+'%'
});
}, false);
return xhr;
},
type: 'post',
processData: false,
contentType: false,
data: fd,
success: function(data) {
var div = $('<div id="progress" class="uk-progress-bar" style="width: 100%;">Done!</div>')
$('#progress').replaceWith(div);
// ** IS THERE SOMETHING I CAN DO HERE TO CLOSE FANCYBOX NOW THAT THE IMAGE UPLOAD IS COMPLETE? **
}
});
});
</script>

The command to close fancybox is $.fancybox.close()
If the progress bar is in an IFrame within the fancybox, you'll need to use parent.$.fancybox.close()
Replacing your comment in the success method with the appropriate command should work.

Related

I want to make the success notification and error notification fade after 4 seconds after the notification but have tried doing it not working.

$( document ).ready(function() {
$("#ajaxform").submit(function(e){
var contactdata = $(this).serializeArray();
var submiturl = $(this).attr('action');
var submitbtn = $('#submit');
submitbtn.val('Sending...');
$("#ajaxform :input").prop("disabled", true);
$.ajax({
url: submiturl,
type: 'POST',
dataType: "json",
data : contactdata,
success: function(response){
$('#alert').removeClass('alert alert-success');
$('#alert').removeClass('alert alert-danger');
if(response.status=="true"){
$('#alert').addClass('alert alert-success');
$("#ajaxform :input").prop("disabled", false);
$('#ajaxform')[0].reset();
submitbtn.val('Send');
}else{
$("#alert").addClass('alert alert-danger');
$("#ajaxform :input").prop("disabled", false);
submitbtn.val('Send');
}
$('#alert').html(response.message).slideDown();
}
});
e.preventDefault();
});
});
I want to make the success notification and error notification fade after 4 seconds after the notification but have tried doing it not working. Am new in coding javascript
This part shows the alert:
$('#alert').html(response.message).slideDown();
The code hiding the alert after 4 seconds is missing. You would put it after the code showing the alert. For example:
setTimeout(function() { $('#alert').hide(); }, 4000);
Link to documentation:
https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout

jQuery File Upload with custom Progress event and Ajax GC

I've built into an app a File Upload with Progress bar using jQuery.ajax .
But I'm concerned that I don't understand how garbage collection will handle it and therefore how memory efficient it will be.
For the progress bar, I had to add a custom xhr in order to add a "progress" event.
When will that custom xhr function and 'progress' event handler be cleaned up?
myApp.prototype.uploadFile = function () {
$.ajax({
type : "POST",
url : posturl,
xhr : function () { // custom xhr
var myXhr = $.ajaxSettings.xhr();
this.onSaveProgress(myXhr, file);
return myXhr;
}.bind(this),
contentType: false,
processData: false,
data : postdata,
beforeSend : this.onBeforeSend,
success : this.onSaveSuccess,
error : this.onSaveError
});
},
myApp.prototype.onSaveProgress = function (xhr, file) {
if (!xhr.upload)
return;
xhr.upload.addEventListener("progress", function (e) {
if (e.lengthComputable) {
var percent = Math.floor((e.loaded / e.total)*100) + "%";
$("#progress" + file.id).css("width", percent).text(percent);
}
}, false); // add new progress event handler
}
As you can see, I needed access to the file Object in the 'progress' event handler so I can update the correct progress bar.

Ajax upload progress bar using jQuery

So I don't use jQuery for everything, but I do use it for the good stuff such as AJAX, and right now that son of gun is giving me some issues. Below is a code that should change my upload progress bar while of course uploading.
function uploadProgess(){
var info = document.getElementById('infor');
var images = document.getElementsByName('file[]')[0].files;
$.ajax({
beforeSend: function(XMLHttpRequest){
XMLHttpRequest.upload.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
document.getElementById('progress-bar').style.display="block";
var percentComplete = (evt.loaded / evt.total * 100) + '%';
//Do something with upload progress
document.getElementById('progress').style.width = percentComplete;
}
}, false);
},
type: 'POST',
url: "administration.php?mode=styling&part=pics_management",
data:{method:"upload",file:images},
success: function(response) {
info.innerHTML = response;
},
error:function(response){
info.innerHTML = response;
}
}).done(function(){
window.location.href = window.location.href;
});
}
This function is invoked when we click the submit button of the form.
$('#upload_images').click(function(e){
e.preventDefault();
uploadProgess();
});
But i am getting Uncaught TypeError: Illegal invocation jQuery.js:4 not sure what I did to invoke another property or whatever I did that was "illegal" Can someone explain what is wrong in my code?
This worked perfectly for me... Notes are within code for other users
function uploadProgess(){
//cache our "info" popup element
var info = document.getElementById('infor');
//cache our input element
var images = document.getElementsByName('file[]')[0];
//create a new FormData object (HTML5)
var fileData = new FormData();
//append type is upload
fileData.append("type","upload");
//append method is ajax (only allow ajax uploads)
fileData.append("method","ajax");
//get the files from the input element
var files = images.files;
//loop through the files
for(i=0;i<files.length;i++){
//append to the fileData with name of `file[]` and then the files object for each image
fileData.append('file[]',files[i]);
}
//new ajax request
var request = new XMLHttpRequest();
//event listener progress
request.upload.addEventListener('progress',function(event){
if(event.lengthComputable){
//cache the progress bar
var progress = document.getElementById('progress-bar');
//get our percentage
var percent = (Math.round(event.loaded / event.total) * 100) +"%";
//make the progress bar visible
progress.style.display="block";
//recache for the spinning bar inside progress
progress = document.getElementById('progress');
//change it's width to the percentage of upload
progress.style.width = percent;
}
});
//add event for when the progress is done
request.upload.addEventListener('load',function(event){
//cache progress bar
var progress = document.getElementById('progress-bar');
//hide the progress bar
progress.style.display="none";
});
//for errors we'll use the info element but for now console log it
request.upload.addEventListener('error',function(event){
console.log(event);
});
//open the request
request.open("POST","{URL}");
//set the request header for no caching
request.setRequestHeader("Cache-Control","no-cache");
//send the data
request.send(fileData);
}

Upload Image Using AJAX with Progress Indicator

I am trying to upload an image using AJAX. I have the local URL of my image
and I want to pass that image as a file to the web service to upload.
Suppose i have the local file URL as : file:///accounts/1000/shared/camera/IMG_00000322.jpg
Now using AJAX I want to pass this to webservice,
What will be the best way to do this? I also want show the progress while uploading
Using php in server side.
uploadImage : function(myImageUrl,chatId){
var formData = new FormData();
formData.append("chatId", chatId);
formData.append("fileimage", myImageUrl);
$.ajax(
{
type:"POST",
url:"http://suresh.sp.in/butler/public/uploadimage/getimage",
contentType:"image/png",
dataType:"json",
data:formData,
success:function(uploaded){
console.info(uploaded.status);
},
error:function(error){
console.info(error);
}
});
}
I used that snippet on several of my websites, it handles Multiples files upload, drag and drop, and a progress bar.
HTML
You will need a container to drop your batch of files, in our case it will be #output, and a list of files.
JS
First we will push the dataTransfer to jQuery's event and bind the drop event.
$(document).ready(function(){
// We add the dataTransfer special property to our jQuery event
$.event.props.push("dataTransfer");
// We bind events for drag and drop
$('#output').bind({
"dragenter dragexit dragover" : do_nothing,
drop : drop
});
});
// stop event propagation
function do_nothing(evt){
evt.stopPropagation();
evt.preventDefault();
}
Then we build our update progress function
// Progress bar update function
function update_progress(evt,fic) {
var id_tmp=fic.size;
//id_tmp help us keep track of which file is uploaded
//right now it uses the filesize as an ID: script will break if 2 files have the
// same size
if (evt.lengthComputable) {
var percentLoaded = Math.round((evt.loaded / evt.total) * 100);
if (percentLoaded <= 100) {
$('#'+id_tmp+' .percent').css('width', percentLoaded + '%');
$('#'+id_tmp+' .percent').html(percentLoaded + '%');
}
}
}
Last but not least our drop function
function drop(evt){
do_nothing(evt);
var files = evt.dataTransfer.files;
// Checking if there are files
if(files.length>0){
for(var i in files){
// if its really a file
if(files[i].size!=undefined) {
var fic=files[i];
// We add a progress listener
xhr = jQuery.ajaxSettings.xhr();
if(xhr.upload){
xhr.upload.addEventListener('progress', function (e) {
update_progress(e,fic);
},false);
}
provider=function(){ return xhr; };
// We build our FormData object
var fd=new FormData;
fd.append('fic',fic);
// For each file we build and Ajax request
$.ajax({
url:'/path/to/save_fic.php',
type: 'POST',
data: fd,
xhr:provider,
processData:false,
contentType:false,
complete:function(data){
//on complete we set the progress to 100%
$('#'+data.responseText+' .percent').css('width', '100%');
$('#'+data.responseText+' .percent').html('100%');
}
});
// for each file we setup a progress bar
var id_tmp=fic.size;
$('#output').after('<div class="progress_bar loading" id="'+id_tmp+'"><div class="percent">0%</div></div>');
$('#output').addClass('output_on');
// We add our file to the list
$('#output-listing').append('<li>'+files[i].name+'</li>');
}
}
}
}
That method doesn't work in IE9 or below.
Hope it helped!
Source(in french)
Some infos on progress tracking using XMLHttpRequest
Some infos on the datatransfer prop
EDIT:
PHP
From the server side you can handle the files normally using $_FILES etc...
In order to set the progress to 100% in the complete function your php script must echo the filesize.

jQuery drag and drop image to textarea handle event

I want to make text area that will handle image drop event on it from the desktop.
I found that I could attach event to html element, but it doesn't work properly. I don't find any error, but it doesn't work.
Here is my code:
var imageDragOver = function imageDragOver(evt)
{
console.log('imageDragOver');
evt.stopPropagation();
evt.preventDefault();
}
var imageDrop = function imageDrop(evt)
{
console.log('imageDrop');
evt.stopPropagation();
evt.preventDefault();
}
document.addEventListener($('textarea'), imageDragOver, false);
document.addEventListener($('textarea'), imageDrop, false);
There is no any message in console log. What I do wrong? I don't look for an already made solutions.
To handle drop event on your area (text area or div) you need to do this:
var dropzone = document.getElementById('ta'); // paste your dropzone id here
dropzone.ondrop = function(e){
console.log('drop'); // for debugging reasons
e.preventDefault(); // stop default behaviour
readfiles(e.dataTransfer.files); // function to handle file(s) that was added to dropzone
};
Next you need to send this files to server and show it in the browser if you want.
function readfiles(files) {
var formData = new FormData(); // we initialise a new form that will be send to php
for (var i = 0; i < files.length; i++) { // if we have more that one file
previewImg(files[i]); // function to preview images
formData.append('file'+i, files[i]);
}
formData.append('moreInfo','myValuableValue');// you can append additional string info
$.ajax({
url: './path_to_file_handler.php',
type: 'POST',
data: formData,
async: true,
success: function (data) {
console.log(data);
},
cache: false,
contentType: false,
processData: false
});
}
function previewImg(file) {
var reader = new FileReader();
reader.onload = function (event) {
var image = new Image();
image.src = event.target.result; // set image source
image.width = 550; // a fake resize
document.getElementById('body').appendChild(image); // append image to body
};
reader.readAsDataURL(file);
}
Code for testing path_to_file_handler.php
<?php
print_r($_POST);
print_r($_FILES);
?>
Hope it will help somebody.
A simple way with jQuery UI, check out:
http://jqueryui.com/draggable/
http://jqueryui.com/droppable/
EDIT:
Duplicate of: Drag and drop desktop to browser HTML5 Javascript ?
Good luck! :-)

Categories

Resources