I am turning my comments on wordpress into an ajax driven system.
All is good so far, until I bumped into an issue with the .catch() method firing straight after the .then() method.
Here is my code...
Ajax engine
commentAPI: function(action, encoded, userID) {
let self = this;
return new Promise(function (resolve, reject) {
//console.log("ajax call to " + self.ajaxURL + " with action " + action);
jQuery.ajax({
url: self.ajaxURL,
type: 'post',
data: 'action='+action+'&data='+encoded,
dataType: 'json',
success: function(data, code, jqXHR) { resolve(data); },
fail: function(jqXHR, status, err) { console.log('ajax error = ' + err ); reject(err); },
beforeSend: function() {} //display loading gif
});
});
},
The method handling the comment form submission
handleReplyFormSubmit: function(form) {
let self = this;
this.removeErrorHtml(form);
// Serialize form to name=value string
const formdata = jQuery(form).serialize();
// Validate inputs
// * Wordpress doing this for now and providing error resonse
// Encoode data for easy sending
const encodedJSON = btoa( formdata );
this.commentAPI('dt_submitAjaxComment', encodedJSON).then(function(response){
console.log('firing then');
if( response.error == true ) {
self.printFormError(form, response.errorMsg);
}
else {
let html = response.commentHTML;
console.log('html returned' + html)
jQuery(form).append(html);
Jquery(form).remove();
}
}).catch(function(err) {
console.log('firing catch');
if( err !== undefined && err.length > 0 ) {
self.printFormError(form, err);
}
else {
self.printFormError(form, 'Unkown error');
}
});
return false;
},
The code is doing what it is supposed to, but the catch method is being fired too, which is making error handling frustrating...
Notice how this is being fired
console.log('firing catch')
But this isn't ( within the ajax fail function )
console.log('ajax error = ' + err );
Am I doing something wrong?