title: Download DOCX documents using Ajax
body: <p>I am using the following js script to post variables from a web form to a python script which then generates a docx documents and in turn responds back to the ajax POST to download it, I can successfully get a file however it seems corrupt when trying to open with word(possibly due to mis-encoding), the size of the file is around 300K, but when downloaded the size is 500K</p>
  
  <p>The reason I would like to use the ajax script is so that I can get a full handle of the situation, sometimes the server side python script returns an error and I would like to use ajax to display this to the user to understand what is going on.</p>
  
  <p>How can I modify the js script to properly save the docx file. I have tried different <code>dataType</code> for the ajax post, but I get parse error when using anything but <code>text</code> type.</p>
  
  <p><strong>Code:</strong></p>
  
  <pre><code>var url = $('#myform').attr('action');
  
  var data = $('#myform').serialize();
  
  $.ajax({
      type: "post",
      url: url,
      data: data,
      dataType: 'text',
      success: function(responseData,textStatus, xhr)
      {
          console.log('got response' + textStatus + xhr.getResponseHeader("Content-Disposition"));
          var blob=new Blob([responseData],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"});
          var link=document.createElement('a');
          link.href=window.URL.createObjectURL(blob);
          link.download="test.docx";
          link.click();
      },
      error: function (jqXHR, exception) 
      {
           var msg = '';
          if (jqXHR.status === 0) {
              msg = 'Not connect.\n Verify Network.';
          } else if (jqXHR.status == 404) {
              msg = 'Requested page not found. [404]';
          } else if (jqXHR.status == 500) {
              msg = 'Internal Server Error [500].';
          } else if (exception === 'parsererror') {
              msg = 'Requested JSON parse failed.';
          } else if (exception === 'timeout') {
              msg = 'Time out error.';
          } else if (exception === 'abort') {
              msg = 'Ajax request aborted.';
          } else {
              msg = 'Uncaught Error.\n' + jqXHR.responseText;
          }
          console.log(msg);
      } 
  
  })
  </code></pre>