0
[File 
    { size=295816, type="image/jpeg", name="img_new3.JPG"}, 
 File { size=43457, type="image/jpeg", name="nature.jpg"}
]

this is the data that i received from the script now i have to send only size and the name of the file with to the php file through ajax.
here is my code

            var files = []; 
            files["file"] = [];

            // file is an object that has the above result
            for( var i=0, j=file.length; i<j; i++ ){
                console.log( file[i].name );
                files["file"][i] = file[i].name;
                files["file"][i] = file[i].size;
            }

            // Send Request to Create ZIP File
            console.log(files)

i want to access the params for my PHP file:

file(
    name=>array(
          0=>"name", 
          1=>"size"
    ), 
    size=>array(...)
)

how do i make an array that send the data to PHP file like the above?

3 Answers 3

1

First of all you have to use the Object notation, not Array, and then you can pass it to your PHP function via Ajax.

var files = {};
files["file"] = [];

// file is an object that has the above result
for (var i = 0, j = file.length; i < j; i++ ){
    console.log(file[i].name);
    files["file"][i] = file[i].name;
}

And then use that array with JSON.stringify to pass data to your PHP script like this:

$.ajax({
    url: "your url",
    type: "POST", //can be get also, depends on request
    cache: false, //do you want it to be cached or not?
    data: {files: JSON.stringify(files)},
    success: function(data) {
        //do something with returned data
    }
});

Anyway I suggest you changing the way you store your data. Objects are very useful in this case:

var files = [];

// file is an object that has the above result
for (var i = 0, j = file.length; i < j; i++ ){
    console.log(file[i].name);
    files.push({
        name: file[i].name //you can add all the keys you want
    });
}
Sign up to request clarification or add additional context in comments.

Comments

0

You have js array ready so just use the jQuery post method to send the created array to the php file which then processes the array the way you want it to.

Comments

0

Your multidimensional array can be JSON encoded and sent as a string via ajax to the PHP script, which can decode the JSON back to an array/object:

// assuming the array is in files var
$.ajax({
    url : 'page.php',
    type : 'POST',
    data : { myFiles : JSON.stringify(files) },
    success : function(response){
        console.log("successfull");
    }
});

On the PHP side:

if($_SERVER['REQUEST_METHOD'] == 'POST')
{
    $filesArray = json_decode($_POST['myFiles']);
    print_r($filesArray);
}

Comments

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.