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

2
  • Your checking for not empty $data where is $data set? Commented Sep 4, 2016 at 10:20
  • oh forgot to change variables in code writing thist question, update now Commented Sep 4, 2016 at 10:24

2 Answers 2

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();
});
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, how to do this if use this: window.location.href=URL.createObjectURL(blob);
This is the replacement, the a.click() method will fire the click event and so you get that save dialog. Try it out.
Glad to help out.
document.body.appendChild(a); is unnecessary,it may broken layout
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();
});

3 Comments

could you give me link with example?
Error:"Undefined index: dane" when try to catch array in php file using $_POST['dane'];
@Marcin: Can you please post your updated code? Or can you check the POST request with Chrome DevTools or Firebug?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.