Marcin Marcin - 1 year ago 115
PHP Question

Pass data from js to php and download created csv file

I must pass array from JS to PHP using $.post(), create file using array and download it.

Using this pass array:

$('#csv').click(function () {
window.location + "crawler/save_to_file",
dane: wynik //array

Now in PHP using this:

$filename = "export-to-csv.csv";
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Expires: 0");
$fh = fopen( 'php://output', 'w' );
$heading = false;
foreach($tablica as $row) {
if(!$heading) {
fputcsv($fh, array_keys($row));
$heading = true;
fputcsv($fh, array_values($row));

But when click on button to create and download file, nothing happens.



JS file:

url: window.location + "crawler/",
type: "POST",
dataType: "json",
data: {
wartosc: zmienna
success: function (odp) {
wynik = odp; //array
tab = JSON.stringify(odp);
$.post(window.location + "crawler/return_data",
data: tab
function (data) {

$('.button').click(function() {
var $form = $('<form action="' + window.location + 'crawler/save_to_csv" method="post"></form>');
$.each(wynik, function() {
$('<input type="hidden" name="dane[]">').attr('value', this).appendTo($form);

And var_dump array in PHP file:

function save_to_csv()


return: "Undefined index: dane"


$tablica must be

Answer Source

This can be done with AJAX but you need to use the File api. So you do something like this:

$.post("csv.php", {
     dane: wynik //array
}, function(response){
   var blob = new Blob([response], { type:'text/csv' });

The url you get from the alert, contains your csv file.

And of course if you want to go directly to the file you replace the alert with:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download