I have a button [Download Document] which does these two things:
- Makes an ajax call and populates a table with data.
-
Postsubmits a form which:a. Runs a back-end script that creates a document
b. Returns the document to the browser in a way that the browser downloads the document.
One problem. The post submit is not ajax, which means that the browser treats it the same way as clicking on a link, refreshing a page, or closing the window, e.g. it cancels the ajax request without even getting a response error.
Using .preventDefault() on the button doesn’t work. It does allow the ajax call (1) to complete successfully, but then the form isn’t submitted, so (2) the form is never submitted.
<form action="/backendScript" method="post">
<input type="submit" value="Download Document">
</form>
$(".downloadBtn").on("click", function (e) {
generateTable();
e.preventDefault(); // without this, the ajax in generateTable(); is cancelled, but with it, the form isn't submitted.
});
Doing (2) with an ajax post also doesn’t work. It can complete (2.a), but the returned document goes straight to Javascript, instead of the browser, and Javascript isn’t able to cause a download event, so (2.b) fails with this approach.
$.post("/backendScript", formData, function (generatedDoc) {
console.log(generatedDoc); //yay, here's our doc! but how do we download it??
});
So it looks like I must post submit the form. But how can I prevent this from canceling any ajax requests that are in progress?
In the success/error/whatever response event you want from your ajax call in
generateTable, submit the form. Eitherdocument.forms["myform"].submit();or$('#myform').submit();(depending on if you want to use vanilla js or jQuery).