Marcin Marcin - 2 months ago 23
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 () {
$.post(
window.location + "crawler/save_to_file",
{
dane: wynik //array
});
});


Now in PHP using this:

$tablica=$_POST['dane'];
$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;
if(!empty($tablica))
foreach($tablica as $row) {
if(!$heading) {
fputcsv($fh, array_keys($row));
$heading = true;
}
fputcsv($fh, array_values($row));
}
fclose($fh);


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

Thanks

CODE UPDATE

JS file:

$.ajax({
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) {
$('#wynik').html(data);
$('.pobierz').show();
}
)
}
})


$('.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);
});
$form.appendTo('body').submit();
});


And var_dump array in PHP file:

function save_to_csv()
{
$tablica=$_GET['dane'];
var_dump($tablica);

}


return: "Undefined index: dane"

EDIT

$tablica must be
$_POST
not
$_GET

Answer

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' });
   alert(URL.createObjectURL(blob));
});

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:

window.location.href=URL.createObjectURL(blob);
Comments