I've been working on converting my WordPress comments into an ajax-driven system.
Everything was going smoothly until I encountered a problem with the .catch() method triggering right after the .then() method.
Below is the code snippet...
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 responsible for 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
// Encode 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 seems to be functioning as intended, but the catch method is getting triggered unnecessarily, causing frustration with error handling...
https://i.sstatic.net/FNopj.png
It's interesting to see how this part of the code gets executed:
console.log('firing catch')
While this one doesn't (within the ajax fail function):
console.log('ajax error = ' + err );
Am I missing something here?