3

I use the Ajax JQuery command to call a PHP script that generates a CSV file and returns a link to that file for the user to download.

I would like to make this more user friendly by automatically starting the download so the user sees the browsers "Save or Open" window instead of having to click the download link.

I'm guessing I need to somehow change the headers in the Ajax success callback function??

I'm not really sure what I should be titling my searches or even if this is possible.

Thanks!

krx
  • 2,643
  • 4
  • 28
  • 29
  • 2
    Sounds like you'd actually want to *not* do AJAX in this case, and set the document location to the query string to generate that CSV. (Or, if you like popups, popup a new window/tab to the CSV location.) – Conspicuous Compiler Mar 20 '10 at 00:16
  • 1
    Doing it the AJAX way, retrieve the `url` from server and set document location to `url` – N 1.1 Mar 20 '10 at 00:21
  • 1
    agree with krio. Best practice for this is to not do async postback but to update the url. That also you user might want to save that link and download it later without returning to the page. – makeitmorehuman Mar 20 '10 at 00:22
  • Thanks for the useful comments all! I took a little of what everyone said and found a solution! – krx Mar 20 '10 at 00:44

1 Answers1

3

You can do this easiest (and possibly only) server-side, no need for ajax, like this:

<?php
header('Content-type: "text/csv"; charset="utf8"'); //adjust encoding if needed
header('Content-disposition: attachment; filename="fileNameHere.csv"');
//output document in response
?>

Someone feel free to edit this if the syntax if off, it's been quite a while since I've had a php project.

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155