Refactored the error handler in ajax_submit
Background
I was having problems with some experimental work regarding ajax_submit and using custom error classes for error handling/logic flow in the back end.
I noticed that if I used an HTTP error response to pass an error message through to the front end when processing a form, the message was ignored and a generic one shown instead.
By comparison, if I used an HTTP success response but included 'result' : 'error'
in the object returned, that worked fine.
After a lot of head scratching, I found that the ajax_submit error handler from Zon core is written to expect the argument pattern of an $.ajax() success handler — that's why the second case worked. In that second case, the original 'success' arguments are passed through to the error handler function in the order it is written to expect.
In the first case, however, the HTTP error response results in $.ajax()
's different arguments being passed directly to ajax_submit
's error_handler method, and things go awry because they are not in the order it expects. Also, the response
object that we need to use is actually wrapped up as jqXHR.responseJSON
.
What I did
- Moved the bulk of the error handling function to a new
core_error_handler()
function, with unchanged argument expectations. - Added a new
error_handler
function that expects the arguments it will get from$.ajax().error()
, unwraps the JSON-encodedresponse
, and then calls the maincore_error_handler()
- Changed the success handler function to call the main
core_error_handler()
when it detects a soft error.
Implications
- AJAX Submit should now be more agnostic about accepting 'hard' or 'soft' errors.
- Not 100% confident that this is the best way to deal with this issue, certainly up for further discussion.
- There may be edge cases that I'm not aware of.
- I have targeted this merge at my experimental branch, but if this is a good solution we should look at bringing it into zon core. It should be fully independent of the other work I'm doing.
Setup
- Suggest testing this with the AFES branch I'm working on: patch/refactor_donate_method, commit 8f6519252a5d57d34594da7f2f2dd6680f22b364
How to test
- Use the "donated before" form, accessible from the button on the right.
- Enter invalid name and email address, e.g.
xxxxxxx@customd.com
- Observe that the 'error' message is delivered as an error 500 HTTP response, and shows to the user OK.
- In
controllers/api/v1/fmsync.php
, change line 218 to the following code, to test behaviour when the same message is delivered as a 'success' response:
output_json(array(
'result' => 'error',
'errors' => array('Sorry, we could not match your name & email.')
));