0

This might be a bad question, because it's possible the issue is to something else in my project, but I was hoping that changing the header from an AJAX call may be an issue someone is familiar with. The below PHP function executes fine when called synchronously, but does not download anything and returns a 200 error when I call it from AJAX.

  public function download_csv() {

    $csv = 'hello, header';
    header('Content-Disposition: attachment; filename="format.csv"');
    header('Content-Type: text/plain');
    header('Content-Length: ' . strlen($csv));
    header('Connection: close');


    echo $csv;
  }
ab11
  • 19,770
  • 42
  • 120
  • 207
  • 1
    A 200 error? A response code of 200 isn't an error, it's an OK – Mark Baker Jul 02 '15 at 11:40
  • 1
    But if you're calling this via an Ajax request, how is your Ajax handling the response? – Mark Baker Jul 02 '15 at 11:41
  • `HTTP Status Code 200` is `OK`, It indicates that the request was successful and the server was able to deliver on the request. – Magicprog.fr Jul 02 '15 at 11:41
  • ok, sorry. it returns without error then. (but nothing gets downloaded). I will look into CrisDeBlonde's suggestions. – ab11 Jul 02 '15 at 11:45
  • The file gets downloaded and made available to the XHR object. It isn't saved to the disk because you are handling it with XHR. – Quentin Jul 02 '15 at 11:46
  • I don't understand this comment. Is there a way to use the XHR Object to download to disk? – ab11 Jul 02 '15 at 11:53

1 Answers1

2

In my knowledge you cannot download a file using ajax (security reasons).
I googled a bit again, and it seems that this is the point.

A working solution could be using an iframe that is not visible to the user, and setting its 'src' attribute to the download url when you need to download the file.

You can also check this answer here that uses a jquery plugin and looks promising (haven't tried it myself)

Community
  • 1
  • 1
CdB
  • 4,738
  • 7
  • 46
  • 69
  • I encountered `$.fileDownload` for the first time just yesterday, and it does look very promising, but I have yet to test it properly – Mark Baker Jul 02 '15 at 11:47
  • So, say I put a hidden iframe in my html. What next? I'm not downloading a file from a URL, just converting a string to csv to be donwloaded. I could make an AJAX call to retrieve the string, and set the `src` attr in javascript. But would I be able to set it without a url? – ab11 Jul 02 '15 at 12:02
  • I'm not sure I understand your comment. You provided some php code which results in serving a csv file. If you set the iframe's src to the location where this code is executed, then the csv will get downloaded - without leaving the page user is currently viewing. Is that not the case? – CdB Jul 02 '15 at 12:07