I have an AJAX request which shows a modal window with a progress bar when the data is computable but if there is an error I would like the error to be returned and the modal window to stay hidden.
$(document).ready(function(){
$(function () {
var pleaseWait = $('#pleaseWaitDialog');
showPleaseWait = function () {
pleaseWait.modal('show');
};
hidePleaseWait = function () {
pleaseWait.modal('hide');
};
});
var $myForm = $('.form')
$myForm.on('submit', function(event){
event.preventDefault();
var form = $(event.target)
var formData = new FormData(form[4]);
$.ajax({
xhr: function() {
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
showPleaseWait(); // <--------------- This runs even when view returns error
console.log('Percentage uploaded: ' + (e.loaded / e.total))
var percent = Math.round(e.loaded / e.total * 100);
$('#progress-bar').attr('aria-valuenow', percent).css('width', percent + '%');
}
});
return xhr;
},
type: 'POST',
url: form.attr('action'),
enctype: 'multipart/form-data',
processData: false,
contentType: false,
data: new FormData(this),
success: function(data){
if (data.success) {
window.location.href = data.url;
}
if (data.error) {
$("#top").html(data.error.title).addClass('form-field-error');
$("#div_id_title").removeClass('form-group');
}
},
});
});
});
I have tried moving the showPleaseWait
function under the if(data.error)
statement but this doesn’t work.
How do I keep the modal window hidden if the response is (data.error)
?
EDIT:
And this removes the HTML of the page and shows the JSON response instead:
success: function(data){
if (data.success) {
window.location.href = data.url;
}
error: function (jqXHR, exception) {
if (data.error) {
$("#top").html(data.error.title).addClass('form-field-error');
$("#div_id_title").removeClass('form-group');
}
}
},
2
Answers
Your function is the “succes” property of the ajax object.
As shown in the doc, there is a “error” property to handle ajax error, here is the signature :
Use it like you do with the succes property :
I hope it solved your issue !
$.ajax() doc
I think you are using Jquery 3.0
so try this
// Perform other work here …
// Set another completion function for the request above
jqxhr.always(function() {
alert( “second complete” );
});