0

I am trying to send JavaScript array to PHP script using Ajax but when i try to var_dump $_POST['file_paths'] getting string instead of array as an output, i want output in array format not in string format. is it because of Ajax setting i am using in code like contentType: false and processData: false.

i tried JSON decoding and encoding still getting string as an output , if anyone can point me in right direction.( need output in array format not in string)

HTML Markup : (folder upload)

<form id='submit' action='' method="post">
            <div id="upload">
                <div class="fileContainer">

                    <input id="myfiles" type="file" name="myfiles[]" multiple="multiple" webkitdirectory multiple directory />
                </div>
            </div>
            <input id="directory_name" type="text" name="directory_name" placeholder="Directory Name" >
</form>

This is simple js to fetch all form data like parent directory name , and file data and file path using

webkitRelativePath

after fetching all data sending two array 1st is file array and second is file_paths array to php script, when i console.log file_paths array getting array.

JS script:

            $(document).ready(function() {
                $('#myfiles').on("change", function() {

                    var myfiles = document.getElementById("myfiles");
                    var file_paths = [];
                    var files = myfiles.files;
                    var new_directory_name =$('#directory_name').val();
                    var data = new FormData();
                    data.append('new_directory_name',new_directory_name);
                    data.append('action', 'upload_folder_to_server');
                    data.append('data_room_id', 55);
                    data.append('username', 'saurabh');
                    for (i = 0; i < files.length; i++) {
                        data.append('file' + i, files[i]);
                        file_paths.push(files[i].webkitRelativePath);
                        console.log(files[i].webkitRelativePath);
                    }
                    //file_paths = JSON.stringify(file_paths);
                    console.log(file_paths);
                    data.append('file_paths', file_paths);
                    $.ajax({
                        method: "POST",
                        url: ajaxurl,
                        contentType: false,
                        data: data,
                        processData: false,
                        //cache: false
                    }).done(function(msg) {
                        $("#loadedfiles").append(msg);
                    });
                });
            });

javascript output:

Array(3) [ "first folder/second folder/third folder/upload_groupmembers_additonal_login_sample(7).xlsx", "first folder/second folder/upload_groupmembers_additonal_login_sample(7).xlsx", "first folder/upload_groupmembers_additonal_login_sample(7).xlsx" ]

In PHP Script when var_dump file_paths getting output in string format. PHP Script:

function upload_folder_to_server()
{
    var_dump($_POST['file_paths']);
}
add_action('wp_ajax_upload_folder_to_server', 'upload_folder_to_server');
add_action('wp_ajax_nopriv_upload_folder_to_server', 'upload_folder_to_server');

Output:

string(232) "first folder/second folder/third folder/upload_groupmembers_additonal_login_sample(7).xlsx,first folder/second folder/upload_groupmembers_additonal_login_sample(7).xlsx,first folder/upload_groupmembers_additonal_login_sample(7).xlsx" 

can someone explain me why i am getting string in PHP and array in JavaScript

  • Does this answer your question? [How to pass a Javascript Array via JQuery Post so that all its contents are accessible via the PHP $\_POST array?](https://stackoverflow.com/questions/5571646/how-to-pass-a-javascript-array-via-jquery-post-so-that-all-its-contents-are-acce) – Gricey Feb 17 '20 at 08:02
  • thanks for you comment ,but my concern is not geting JavaScript array in PHP but getting output in similar format, e.g. if i send array through JavaScript but getting string in PHP script , i want array as output if i send array in JavaScript and little explanation why i am getting string instead of array – Do Not Panic Feb 17 '20 at 08:09

2 Answers2

0
  var myfiles = document.getElementById("myfiles");
                    var file_paths = [];
                    var files = myfiles.files;
                    var new_directory_name =$('#directory_name').val();
                    var data = new FormData();
                    data.append('new_directory_name',new_directory_name);
                    data.append('action', 'upload_folder_to_server');
                    data.append('data_room_id', 55);
                    data.append('username', 'saurabh');
                    for (i = 0; i < files.length; i++) {
                        data.append('file' + i, files[i]);
                        file_paths.push(files[i].webkitRelativePath);
                        console.log(files[i].webkitRelativePath);
                    }
                    //file_paths = JSON.stringify(file_paths);
                    console.log(file_paths);
                    data.append('file_paths', file_paths);

replace with this and try

var myfiles = document.getElementById("myfiles");
var file_paths = [];
var files = myfiles.files;
var new_directory_name =$('#directory_name').val();
var data = new FormData();
data.set('new_directory_name',new_directory_name);
data.set('action', 'upload_folder_to_server');
data.set('data_room_id', 55);
data.set('username', 'saurabh');
for (i = 0; i < files.length; i++) {
data.set('file' + i, files[i]);
file_paths.push(files[i].webkitRelativePath);
console.log(files[i].webkitRelativePath);
}
data.set('file_paths', file_paths);
0

You should be able to do it with JSON.stringify() and json_decode().

Stringify it before sending it with JS:

const jsonArr = JSON.stringify(data);

Parse it when you receive it on the PHP end:

$parsedArr = json_decode($_POST['file_paths']);

OR

What you can do is to convert the string to an array when you receive it on the PHP end.
All you need to do is to simply add this:

$str = isset($_POST['file_paths']) ? $_POST['file_paths'] : ''; // Use condition to check if there is a post request with that name coming in
$arr = explode(",", $str);

In the first parameter of the explode() function you can specify where you want the string to split. Read more here.

Ludolfyn
  • 1,806
  • 14
  • 20