0

Here is my code:

    $(document).on('click', '#csv_export', function () {

        // I need to pass this array to where the form below submits
        var arr = ['item1', 'item2'];

        $('<form action="csv_export/person?filename=export.csv" method="POST"/>')
        .append($('{!! csrf_field() !!}<input type="hidden" name="type" value="save">'))
        .appendTo($(document.body)) //it has to be added somewhere into the <body>
        .submit();
    });

As I've commented in my code, there is arr that I need to pass it to that page the form points out. How can I do that?


Noted that I can putting this in the form:

<input type="hidden" name="arr" value="'+arr+'">

But I it has two problems:

  1. character length limitation
  2. the result will be a string. (while I need an array in the server side)
Martin AJ
  • 6,261
  • 8
  • 53
  • 111

1 Answers1

0

Convert the array to JSON with JSON.stringify(). And instead of constructing the input as a string, use a jQuery function to do it:

$('<form action="csv_export/person?filename=export.csv" method="POST"/>')
    .append($('{!! csrf_field() !!}'))
    .append($("<input>", {
        type: 'hidden',
        name: 'arr',
        value: JSON.stringify(arr)
    });
).appendTo('body')
.submit();

In the PHP script, use json_decode($_POST['arr'], true) to get the array.

You should also be able to use AJAX:

$.post('csv_export/person?filename=export.csv', { arr: JSON.stringify(arr) });

For a small array, you could just use { arr: arr } and then access $_POST['arr'] as an array. But when you pass an array like this, each element becomes a separate post parameter, and by default PHP only allows 1000 parameters. You can change this in php.ini, but using JSON is probably a simpler solution for this case.

Barmar
  • 741,623
  • 53
  • 500
  • 612