EML
EML

Reputation: 10281

JavaScript: Is it possible to handle server errors from `form.submit()`?

I normally use Ajax for form submission, but there is one case where this isn't possible. This particular form has to trigger a file download from the server, and the browser must produce a 'save as' dialog. I have to do this the old way (I think), with a form submission that returns an attachment.

To do this, I create a form with JavaScript:

   var form = document.createElement("form");
   form.setAttribute("method", "post");
   form.setAttribute("action", "/cgi-bin/myprog");
   ...create and append lots of input elements, and then
   form.submit();

This works fine, until the server has to return an error. If the server returns 403 Forbidden, for example, then the browser just shows a blank page and tries to redirect to /cgi-bin/myprog.

Is there any way to handle errors with submit()? The W3C spec only seems to say User agents should render the response from the HTTP "get" and "post" transactions. The HTMLFormElement spec doesn't say anything about errors. I control the server, and can change the response, so I could potentially return 200 OK with an error message, but there must be a better way to do it.

Upvotes: 1

Views: 1200

Answers (1)

EML
EML

Reputation: 10281

Basically, it's not possible, so you have to check in advance whether or not the download will succeed. In my case, I only need to check whether the user is authorised to access the file.

I handle this by sending a separate Ajax request to the server, which returns success (200) if the user is authorised, and failure otherwise (403, or whatever). If success is returned (ie. the textStatus parameter to .always is success), then I construct and submit the form as above.

Upvotes: 1

Related Questions