1

I use jquery to set a get query to a php script which then queries the database and writes to the screen, but I can't get it to trigger the download, even with headers.

The steps are as follows:

  1. create a link that the user clicks to download the data

  2. javascript sends the query parameters to php

  3. php queries the database and writes the file

  4. client downloads the file

But I can't get step 4 to happen.

Step 1: (this is a table object that also contains the parameters:

d3.select("#some-div").append('a")
    .attr("href", "javascript: void(0)")
    .on("click", function() { this.saveAsCSV() };

Step 2: Javascript file to make query:

var saveAsCSV = function(params) {
    var tmp_params = $.extend({}, params);
    tmp_params['State'] = "NM";
    $.get('php/get_data.php', tmp_params);
}

php to return query:

...
header("Content-type: application/text-csv");
header("Content-Disposition: attachment; filename=query_result.csv");
while($row = $result->fetchArray() {
    print "$row";
}
...

It works fine in that it correctly queries and will print the data in the javascript function (so it will print it to console.log if I add that into the get return function), but I can't figure out what I should do differently to make it just download it directly.

One thing I've tried is to do the following on the params object:

var param_string = encodeURIComponent(JSON.stringify(params));
location.href = 'http://www.mysite.com"+param_string;

But that both takes the user away from the page and fails to download the data.

EDIT: I should clarify that the php file does output the query well in csv format. The problem seems to be that using the $.get() function does not trigger a download regardless of the php headers. Maybe I need to just provide a simple link with the parameters in the URL address, but I'm not sure how to get a javascript object into a URL format so that the php script can interpret it.

potterzot
  • 638
  • 1
  • 4
  • 11
  • Well there's allready an answer to your question over [here](http://stackoverflow.com/questions/4249432/export-to-csv-via-php) – Devian Jul 02 '13 at 23:25
  • Are ou sure your last suggestion doesn't work? `location.href= 'php/get_data.php'+param_string;` is a valid approach, as long as you don't have the typo you show here (notice the double quotes instead of single quotes) AND the PHP code returns with a `Content-Disposition: attachment` header. – Steve Jul 02 '13 at 23:28
  • @Devian - that's a completely different question than the one the OP asked here. – Steve Jul 02 '13 at 23:29

3 Answers3

2

You could open a popup/new window/tab/whatever with your URL php/get_data.php?State=NM (perhaps additional parameters). It should download the output.

But your output might be wrong because you just print the variable $row which is an array. If you try to print an array that way it will just show Array.

You will need to properly output your rows. Unfortunately I don't know the CSV structure well enough to help you with that problem.

fehnomenal
  • 509
  • 3
  • 10
  • thanks! The $rows variable is just an example to get the point across, but the output looks exactly right from the javascript console, it just doesn't get saved. I think that the issue lies in the $.get(); function, which takes the results. It is supposed to be enough to just link to the page, but perhaps my encoding attempt is wrong. – potterzot Jul 02 '13 at 23:24
0

You can make an AJAX call for this using something like jQuery and it will pop up the download box while keeping the user on the page. Do something like this:

$.ajax({data: {download: 'query_result.csv'}, type: 'GET', url: 'download.php', cache: false });

I've tried this a few times for a previous employer and it always worked great. Although I did it mostly with .zip and .docx files.

Aaron Cunnington
  • 1,631
  • 2
  • 15
  • 23
  • Thanks for the thought. I think that would work well except that in this case I'm outputting the file directly to output rather than saving it on the server first, so there is not 'query_result.csv' file to link to. But I just figured out a solution that I will edit my above post to include. – potterzot Jul 02 '13 at 23:33
0

I figured it out!

Basically, my encoding was wrong. I don't want to encode with

encodeURIComponent(JSON.stringify(params));

The result isn't readable by the php script. However, it works to just use $.param().

To summarize, the download is triggered by creating the URL link and then using location.href to link to it. Hence everything else is the same, but instead of the $.get() in step 2, I do:

var url_params = $.param(tmp_params);
location.href = url_params;

Which generates the download. Thanks!

potterzot
  • 638
  • 1
  • 4
  • 11