2

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

Marcin
  • 243
  • 3
  • 20

2 Answers2

5

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);

UPDATE

If you want to use a custom filename, there is a way to mask the url generated by URL.createObjectURL(), by using an a element. We than can use the new HTML5 attribute download which allows us to mask the url.

Here is the updated code:

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

    // Put the link somewhere in the body
    document.body.appendChild(a);
    a.innerHTML = 'download me';
    a.href = url;
    // Set our custom filename
    a.download = 'myfilename.csv';
    // Automatically click the link 
    a.click();
});
MarcHoH
  • 340
  • 1
  • 6
0

Are you forced to use AJAX to send that array to your PHP code? If yes, it is not really possible.

If not, instead of your AJAX call, you could build a hidden form with hidden inputs containing your array items and submit it via JavaScript.

UPDATE Short example for form built with JS:

$('#csv').click(function() {
  var $form = $('<form action="' + window.location + 'crawler/save_to_file" method="post"></form>');
  $.each(wynik, function() {
    $('<input type="hidden" name="dane[]">').attr('value', this).appendTo($form);
  });
  $form.appendTo('body').submit();
});
Community
  • 1
  • 1
Zoli Szabó
  • 4,366
  • 1
  • 13
  • 19