I have a url that returns either a file or, on error, a JSON response. When the request is acceptable, it responds with a file and the user should be prompted for download (as one might expect in that situation). When there's a problem with the request, the response is a JSON object which should be processed further via javascript.
The request is made via javascript (AJAX, opened in new tab, generated iframe, whatever). How might I go about handling both kinds of responses from the same url via javascript?
The strategy I'm current tinkering with (haven't got working yet) is:
- Generate an iframe
- Inject a form into the iframe
- Set the
error
event handler on the iframe - Trigger submission of the form (I have control over the response headers so I can use
Content-Disposition: attachment
to force the save dialog.) - If the
error
event handler is triggered, scrap the iframe for the json response
Turns out error
events aren't fired by iframes and load
events aren't fired in certain browsers when the iframe is pointed to a file that triggers a save dialog.