Note that there are some explanatory texts on larger screens.

plurals
  1. POPreventing a form post submit download from cancelling Ajax actions
    primarykey
    data
    text
    <p>I have a button <strong>[Download Document]</strong> which does these two things:</p> <ol> <li>Makes an ajax call and populates a table with data.</li> <li><p><code>Post</code> submits a form which:</p> <p>a. Runs a back-end script that creates a document</p> <p>b. Returns the document to the browser in a way that the browser downloads the document.</p></li> </ol> <p>One problem. The <code>post</code> 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, <strong>e.g. it cancels the ajax request without even getting a response error</strong>.</p> <p>Using <code>.preventDefault()</code> on the button doesn't work. It does allow the ajax call (<strong>1</strong>) to complete successfully, but then the form isn't submitted, so (<strong>2</strong>) the form is never submitted.</p> <pre><code> &lt;form action="/backendScript" method="post"&gt; &lt;input type="submit" value="Download Document"&gt; &lt;/form&gt; $(".downloadBtn").on("click", function (e) { generateTable(); e.preventDefault(); // without this, the ajax in generateTable(); is cancelled, but with it, the form isn't submitted. }); </code></pre> <p>Doing (<strong>2</strong>) with an ajax <code>post</code> also doesn't work. It can complete (<strong>2.a</strong>), but the returned document goes straight to Javascript, instead of the browser, and Javascript isn't able to cause a download event, so (<strong>2.b</strong>) fails with this approach.</p> <pre><code> $.post("/backendScript", formData, function (generatedDoc) { console.log(generatedDoc); //yay, here's our doc! but how do we download it?? }); </code></pre> <p>So it looks like I <em>must</em> <code>post</code> submit the form. But how can I prevent this from canceling any ajax requests that are in progress?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload