Abort a multiple file upload AJAX request - javascript

I am trying to abort a multiple file upload with a progress bar, showing the state of the process.
What I want to achieve is to completely abort the multiple file upload on the abort button click; to stop the progress bar as well as to clear every file(s) that might have been uploaded during the course of the initially triggered multiple file upload process.
Below is my code:
var AJAX = $.ajax({
xhr: function() {
var XHR = new window.XMLHttpRequest();
XHR.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
var PROGRESS = Math.round((e.loaded/e.total)*100);
$('#PROGRESS_BAR').text(PROGRESS);
} }, false); return XHR; },
url : '/php.php',
type : 'POST',
data : DATA,
cache : false,
processData: false,
contentType: false,
beforeSend : function() { },
success : function() { }
});
$(document).on('click', '.ABORT', function(e) {
AJAX.abort();
});
I use the code above to dynamically upload images with a progress bar.
I found lots of articles using .abort() to stop the process, but that seemed to only work browser side and not server side.
In what way can I cease the upload completely as in: on both client and server side as .abort() does not enable me get the desirable result?

Try this:
var XHR = new window.XMLHttpRequest();
var AJAX = $.ajax({
xhr: function() {
XHR.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
var PROGRESS = Math.round((e.loaded/e.total)*100);
$('#PROGRESS_BAR').text(PROGRESS);
} }, false); return XHR; },
url : '/php.php',
type : 'POST',
data : DATA,
cache : false,
processData: false,
contentType: false,
beforeSend : function() { },
success : function() { }
});
$(document).on('click', '.ABORT', function(e){
XHR.abort();
});

Related

Jquery Ajax Upload with progress is reloading page

I have strange stuf with a Jquery form submit.
After the upload completed, the page is reloading even in the server has not finished to process.
The server just return a json succes status, so It's not on server side.
Here"s the code:
$form.on('submit', function (e) {
console.log('Submit form ' + fileNumber);
if ($form.hasClass('is-uploading')) return false;
$form.addClass('is-uploading').removeClass('is-error');
if (isAdvancedUpload) {
e.preventDefault();
e.stopPropagation();
var ajaxData = new FormData($form.get(0));
var $input = $form.find('input[type="file"]');
if (fileToUpload) { ajaxData.append($input.attr('name'), fileToUpload); }
console.log('FileTo Upload: ' + fileToUpload);
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
data: ajaxData,
dataType: 'json',
xhr: function () {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
myXhr.upload.addEventListener('progress', progress, false);
}
return myXhr;
},
cache: false,
contentType: false,
processData: false,
beforeSend: function (xhr,settings) {
},
complete: function (xhr, status) {
xhr.
//$form.removeClass('is-uploading');
//fileNumber++;
//fileToUpload = droppedFiles[fileNumber];
//if (fileToUpload) { $form.submit(); }
},
success: function (data,status,xhr) {
//$form.addClass(data.success === true ? 'is-success' : 'is-error');
//if (!data.success) $errorMsg.text(data.error);
},
error: function (xhr,status,error) {
}
});
} else {
// ajax for legacy browsers
}
});
The issue is here:
xhr: function () {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
myXhr.upload.addEventListener('progress', progress, false);
}
return myXhr;
If I remove return myXhr The page is not reloading after upload, but I have no progress report.
I don't know what to do to prevent reloading.
Thanks.
I found out the issue.
There was no worry with the xhr object.
The issue was coming from Visual Studio Browser Link.
After shuting it down, everything worked perfectly.
Browser link, for an obvious reason was fire a reload of the page.
Will see with the ASP.NET Core team
try change buttin type submit to button and implement click function
eg:
$( "#buttonID" ).click(function() {
//your code
});

How do you upload a single image with Dropzone.js?

Dropzone.js seems to be uploading images as multi-part form data. How do I get it to upload images in the same way an image upload would work with cURL or a binary image upload with Postman?
I'm getting a pre-signed URL for S3 from a server. The pre-singed URL allows an image upload, but not form fields:
var myDropzone = new Dropzone("#photo-dropzone");
myDropzone.options.autoProcessQueue = false;
myDropzone.options.autoDiscover = false;
myDropzone.options.method = "PUT";
myDropzone.on("addedfile", function ( file) {
console.log("Photo dropped: " + file.name );
console.log("Do presign URL: " + doPresignUrl);
$.post( doPresignUrl, { photoName: file.name, description: "Image of something" })
.done(function( data ) {
myDropzone.options.url = data.url
console.log(data.url);
myDropzone.processQueue();
});
});
If I use the returned URL with Postman and set the body to binary and attach the image, then the upload works fine. However, if the Dropzone library uses the same URL to upload the image to S3 then I get a 403 because S3 does not expect form fields.
Update:
An Ajax alternative works as below with a S3 signed url, but Dropzone.js does not seem willing to put the raw image data in the PUT message body.
$.ajax( {
url: data.url,
type: 'PUT',
data: file,
processData: false,
contentType: false,
headers: {'Content-Type': 'multipart/form-data'},
success: function(){
console.log( "File was uploaded" );
}
});
Set maxFiles to 1.
Dropzone.autoDiscover = false;
dzAllocationFiles = new Dropzone("div#file-container", {
url: "api.php?do=uploadFiles"
, autoDiscover: false
, maxFiles: 1
, autoQueue: true
, addRemoveLinks: true
, acceptedFiles: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
});
dzAllocationFiles.on("success", function (file, response) {
// Success Operations
});
dzAllocationFiles.on("maxfilesexceeded", function (file, response) {
allocationFileNames = [];
this.removeAllFiles();
this.addFile(file);
});
Add below options, then working.
myDropzone.options.sending = function(file, xhr) {
var _send = xhr.send;
xhr.send = function() {
_send.call(xhr, file);
}
}

How to write code inside ajax without xhr

I have a code like this before:
<script>
function()
{
//*code*
fxajax.sendData
({
url:"",
data:{},
success:function(){},
error:function(){}
});
}
</script>
But my manager wants me to put my code inside the ajax so i put it inside beforeSend
<script>
function()
{
fxajax.sendData
({
beforeSend: function()
{/*code*/}
url:"",
data:{},
success:function(){},
error:function(){}
});
}
</script>
My problem is beforeSend is not executed but url, data, success and error works fine. Then I think maybe its because I don't have an XHR request.
Any idea how I should implement this code?
Here is a simple way
$(document).ready(function(){
// set a 1 second to fire ajax request
setTimeout(function () {
// url of the image
var url = 'https://upload.wikimedia.org/wikipedia/commons/0/02/SVG_logo.svg';
$.ajax({
url : '', // url request
type : "GET", // type of request,
beforeSend : function () {
var i = new Image();
i.src = url;
i.onload = function () {
// change it to div
$('div').append(i);
}
console.log("ajax is firing");
},
success: function () {
},
error : function (xhr, txtstatus, text) {
console.log(txtstatus);
console.log('error');
// any error from request
}
});
}, 1000);
});
Here is a simple DEMO

Jquery filer.js Ajax request not sending updated variable value

so Ive got this jquery plugin which is sending an ajax request to a php file with a variable attached.
However the variable attached to data{type:filetype} is being changed on the page. When the user submits the request to be sent, the new value of the filetype is not being sent.
Any idea why ?
The filetype variable is a global variable :
<script type="text/javascript">
var filetype = "";
</script>
This is the plugin being initiated :
$('#filer_input1').filer({
uploadFile: {
url: "php/fileupload/upload.php",
data: {order:19,
type:filetype},
type: 'POST',
enctype: 'multipart/form-data',
beforeSend: function(){
console.log(filetype);
},
success: function(data, el){
console.log(data);
console.log(el);
},
error: function(el){
},
statusCode: null,
onProgress: null,
onComplete: null
}
}
function which updates the variable :
function setFileType(x){
var text = $("#"+x).html() + ' <span class="caret"></span>';
$("#fileTypeSelect").html(text);
filetype = x;
}
Any help would be greatly appreciated

Tooltip script. Need to correct code

$(function() {
$('.challenge').tooltip({html: true, trigger: 'hover'});
$('.challenge').mouseover(function(){
var that = $(this);
var ajaxQueue = $({
url: "<?=base_url();?>/ajax/challenge_tip",
type: 'POST',
cache: true,
data: {
'idd': $(this).attr("rel"),
},
dataType: 'json',
success: function(challenge_j) {
that.tooltip('hide')
.attr('data-original-title', challenge_j)
.tooltip('fixTitle')
.tooltip('show');
}
});
$.ajaxQueue = function(ajaxOpts) {
var oldComplete = ajaxOpts.complete;
ajaxQueue.queue(function(next) {
ajaxOpts.complete = function() {
if (oldComplete) oldComplete.apply(this, arguments);
next();
};
$.ajax(ajaxOpts);
});
};
});
});
it's my first experience with js and i need some help. for tooltips i use bootstrap tooltips.
when cursor hover on link, script send post data to controller and receive callback data. in the first hover script receives the data, but tooltip doesn't pop up, only the second hover. how i can fix it?
and one more question. can script will send the request only the first mouse hover, and the following hover will use the information from the cache?
and sorry my english ;D
It is hard to test cross domain
Here is what I THINK you need
$(function() {
$('.challenge').tooltip({html: true, trigger: 'hover'});
$('.challenge').mouseover(function(){
var that = $(this);
$.ajax({
url: "<?=base_url();?>/ajax/challenge_tip",
type: 'POST',
cache: true,
data: {
'idd': $(this).attr("rel"),
},
dataType: 'json',
success: function(challenge_j) {
that.tooltip('hide')
.attr('data-original-title', challenge_j)
.tooltip('fixTitle')
.tooltip('show');
}
});
});
});
Create flag for ajax query.
var isTooltipTextEmpty = true;
$('.challenge').mouseover(function(){
if(isTooltipTextEmpty) {
...add ajax query here)
}
}
And you need to trigger tooltip show event, when ajax query is ready like this
.success(data) {
$('.challenge').show();
isTooltipTextEmpty = false; //prevents multiple ajax queries
}
See more here: Bootstrap Tooltip

Categories

Resources