Abort ajax file uploading - javascript

I need to implement AJAX file uploading interruption by click on cancel button.
Here's code which I'm trying to use:
var reqx=null;
function ajax_upload(){
reqx = $.ajax({
type: 'post',
url: "/file.php",
data: new FormData( $('#file')[0] ),
cache: false,
contentType: false,
processData: false,
success: function (data) {
console.log("success");
},
error: function (data) {
console.log("error");
}
})
}
$('input[type=file]').change(function () {
ajax_upload();
});
$('#cancel').click(function(){
if (reqx != null){
reqx.abort();
reqx = null;
}
});
Clicking on Cancel button causes an error:
Uncaught TypeError: reqx.abort is not a function
Need help to find out mistake in my code. Thanks.

IIRC your looking for resolve(). http://api.jquery.com/deferred.resolve/ It causes the deferred to immediately complete and process any done logic.

Related

Why is this AJAX/POST taking precedence over the entire block of code

I am sorry, but I cannot for the life of me figure this out.
function submit_order_form() {
if (typeof storedFiles !== 'undefined') {
jQuery('.overlay-loading').css('visibility', 'visible')
return false;
var formData = new FormData();
for (var key in storedFiles) {
formData.append(key, storedFiles[key]);
}
formData.append("rep", $('#sales_rep').val() );
$.ajax({
url: '/send_invoice.php',
type: 'POST',
data: formData,
dataType: "JSON",
processData: false,
contentType: false,
cache: false,
async: false,
success: function (response) {
jQuery('#new_files_ajax').empty();
jQuery('#new_files_ajax').text(response.message);
jQuery('.overlay-loading').css('visibility', 'hidden')
},
error: function(error) {
jQuery('.overlay-loading').css('visibility', 'hidden')
console.log(error);
}
});
}
}
I want the
jQuery('.overlay-loading').css('visibility', 'visible')
to run before the ajax call, which it does not, the ajax call just goes through fine but that visibility css change never happens until right at the end for 1 second and then goes back again because its called in the success function. If I return false right before the ajax call it works as expected. What in the world am I missing here? Its not async it should be waiting for that visibility call to take place.
Completely stumped.
Are you by any chance calling this function from a button embedded on your HTML markup page inside of the <form> tag? If so, you'll need to pass the event object to the function so you can call event.preventDefault() which will prevent the page from reloading on when the request goes through.
By default when a form is submitted, the browser will automatically refresh, so you're visibility toggle will never work properly since the page is reloaded so the overlay would be rendered back to it's original state of being invisible.
Also just as a side note with the FormData call, you can pass the storedFiles object into the constructor rather than looping through the keys of storedFiles and appending each property to the FormData you created as you're not renaming keys in the form data to pass to the API endpoint.
I can't be sure because I don't have any other code, but you can see how this works.
function submit_order_form() {
if (typeof storedFiles !== 'undefined') {
jQuery('.overlay-loading').css('visibility', 'visible')
setTimeout(function(){
var formData = new FormData();
for (var key in storedFiles) {
formData.append(key, storedFiles[key]);
}
formData.append("rep", $('#sales_rep').val() );
$.ajax({
url: '/send_invoice.php',
type: 'POST',
data: formData,
dataType: "JSON",
processData: false,
contentType: false,
cache: false,
async: false,
success: function (response) {
jQuery('#new_files_ajax').empty();
jQuery('#new_files_ajax').text(response.message);
jQuery('.overlay-loading').css('visibility', 'hidden')
},
error: function(error) {
jQuery('.overlay-loading').css('visibility', 'hidden')
console.log(error);
}
});
}, 0);
return false; // <=========
}
}
Of course, this is temporary and in practice it is recommended to fix the entire code with asynchronous calls. (async: true)

jQuery ajax collision issue

I have been coding an ajax request and i have a problem with it.
var addonUploadForm = $('#addonUploadForm');
var addonUploadFormMessages = $('#addonUploadForm-messages');
$(addonUploadForm).submit(function(e) {
e.preventDefault();
//var formData = $(addonUploadForm).serialize();
//var formData = new FormData($(this)[0]);
var formData = new FormData($('#addonUploadForm')[0]);
$.ajax({
type: 'POST',
url: $(addonUploadForm).attr('action'),
data: formData,
xhr: function() { },
cache: false,
contentType: false,
processData: false // marked line of error
success: function(response) {
$(addonUploadFormMessages).removeClass('error');
$(addonUploadFormMessages).addClass('success');
$(addonUploadFormMessages).html(response);
$('#addonTitle').val('');
$('#addonDescription').val('');
$('#addonFile').val('');
grecaptcha.reset();
},
error: function(data) {
$(addonUploadFormMessages).removeClass('success');
$(addonUploadFormMessages).addClass('error');
grecaptcha.reset();
if (data.responseText !== '') {
$(addonUploadFormMessages).html(data.responseText);
} else {
$(addonUploadFormMessages).html('<div class="alert alert-danger fade in out">×<strong>Error!</strong> An error occured and your message could not be sent.</div>');
}
}
});
});
That is my code and on the marked line there is a missing , and this code works fine apart from doesnt display the request on the page and it instead just takes me to the ajax url but if i put the , in it does nothing when i submit the form no errors, no nothing.
Probably this line causes the error:
xhr: function() { },
without an xhr object you cannot send an ajax request.
So leave out this line.
Also you need to put the "," in at your marked line.
Your url opens because if you leave out the "," the function will throw an error and your e.preventDefault() won't work.
Also I would leave out these lines:
contentType: false,
processData: false
And you should probably escape the html content in this line:
$(addonUploadFormMessages).html(data.responseText);
Hope this helps.
I fixed it i had 2 versions of jquery runnning with noconflict and they where 1.11 and 1.4, and 1.4 was last loaded before this. So i had to change my no conflict to var jq1 = jQuery.noConflict(true); and then my ajax code to
var addonUploadForm = $('#addonUploadForm');
var addonUploadFormMessages = $('#addonUploadForm-messages');
$(addonUploadForm).submit(function(e) {
e.preventDefault();
var formData = new FormData($('#addonUploadForm')[0]);
jq1.ajax($(addonUploadForm).attr('action'), {
type: 'POST',
url: $(addonUploadForm).attr('action'),
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(response) {
$(addonUploadFormMessages).removeClass('error');
$(addonUploadFormMessages).addClass('success');
$(addonUploadFormMessages).html(response);
$('#addonTitle').val('');
$('#addonDescription').val('');
$('#addonFile').val('');
grecaptcha.reset();
},
error: function(data) {
$(addonUploadFormMessages).removeClass('success');
$(addonUploadFormMessages).addClass('error');
grecaptcha.reset();
if (data.responseText !== '') {
$(addonUploadFormMessages).html(data.responseText);
} else {
$(addonUploadFormMessages).html('<div class="alert alert-danger fade in out">×<strong>Error!</strong> An error occured and your message could not be sent.</div>');
}
}
});
});

Loader not disappearing after AJAX result is received

I have page that displays data through AJAX, till the time the result is being fetched I wish to display a loader and as soon as the result is fetched I want that the loader should disappear. Below is part of the code where I am trying to display the loader
var onSubmit = function(e)
{
var txtbox = $('#txt').val();
var hiddenTxt = $('#hidden').val();
$("#walkaway").hide();
$("#submitamt").hide();
$("#xtrabutton").hide();
LodingAnimate();
$.ajax(
{
type: 'post',
url: 'test2.php',
dataType: 'json',
data: {txt: txtbox,hidden: hiddenTxt},
cache: false,
success: function(returndata)
{
$('#first').html(returndata[0]);
$('#second').html(returndata[0]);
$('#third').html(returndata[0]);
},
error: function()
{
console.error('Failed to process ajax !');
}
});
function LodingAnimate()
{
$("#maillist").html('<img src="img/ajax-loader.gif" /> Please Wait Loading...');
}
};
On click of a button the above AJAX is executed, after the click the loader runs but even after I get the reply(in console) the loader keeps on running, but in actual it should have disappeared.
You should hide/remove the loader manually after ajax call completes, add Jquery Complete call back and add the code to remove the loader in it.
Jquery Complete - This call back will execute after success and error call back executed.
$.ajax(
{
type: 'post',
url: 'test2.php',
dataType: 'json',
data: {txt: txtbox,hidden: hiddenTxt},
cache: false,
success: function(returndata)
{
//Success code
},
error: function()
{
//error code
},
complete:function()
{
//This block will execute after success/error executes.
//Make the loader div empty
$("#maillist").empty();
}
});

Uncaught TypeError: Cannot read property 'appendChild' of undefined after Ajax call

I wanted to replace my html with the new Ajax response html but this error shows in the console and my script files are not loading correctly. Apparently this error comes in the file "jquery-1.10.1.min.js". Following is my ajax code which I used to replace with the html in the success function.
$(function() {
$('#addcustomer-done').click(function() {
var formData = new FormData($('#submit_form')[0]);
//---------------------- AJAX CALL 1 -----------------------------------------//
$.ajax({
// headers : {
// 'X-CSRF-Token' : document.getElementsByName('csrfmiddlewaretoken')[0].value
// },
url : "/savecustomer/",
type : "POST",
data:formData,
contentType: false,
cache: false,
processData: false,
async: false,
cache:false,
contentType: false,
processData: false,
success : function(data) {
alert(data);
$("html").html("");
$("html").html(data);
}
I'm a beginner at ajax. Kindly guide me how to get rid of this error. Thanks in advance.
Dont clear the elements inside html tags. Use an element present in the dom to append the value. Also remove async:false from your ajax. Because ajax should run asynchronously.
$(function() {
$('#addcustomer-done').click(function() {
var formData = new FormData($('#submit_form')[0]);
$.ajax({
url: "/savecustomer/",
type: "POST",
data: formData,
success: function(data) {
console.log(data);
$("#id of element inside tab").append(data);
}
});
});
});

IE 9, 10, 11 - Ajax calls not returning

I am having an issue with IE related to jQuery and ajax. Chrome and Firefox work just fine, but my ajax calls are disappearing in IE.
After making the ajax call, neither the success nor the fail functions are being called. I can see the response in the IE console, and I know my controller action is being hit.
$.ajax({
url: controllerUrl
type: 'POST',
dataType: 'json',
cache: false,
data: {
id: customerId
},
success: function () {
alert('success!');
},
error: function () {
alert('failed!');
}
});
Has anyone else seen this issue?
fail: function () {
alert('failed!');
}
fail is not a valid jQuery ajax setting. I believe you are looking for error.
Also, cache: false, does nothing with POST requests.
Note, jQuery does not append the time stamp with POST requests.
The source code clearly demonstrates this. (summarized from https://github.com/jquery/jquery/blob/master/src/ajax.js)
var rnoContent = /^(?:GET|HEAD)$/;
s.hasContent = !rnoContent.test( s.type );
if ( !s.hasContent ) {
/* code to append time stamp */
}
You are missing a comma , after your URL parameter:
$.ajax({
url: controllerUrl, // <--- you were missing this comma!
type: 'POST',
dataType: 'json',
cache: false,
data: {
id: customerId
},
success: function () {
alert('success!');
},
error: function () {
alert('failed!');
}
});

Categories