Posted image, plain and array data to php shows [object, object]

Pankaj :

About the issue

I am posting three things

  1. plain text
  2. Array of some plain text
  3. Image

While reading the posted data in php, I was only able to read [object, object] for the array data.

Below is the code in JQuery

Preparing the data to post to a php file.

var items = [];

$(Items).each(function(index, row) {
    var name = $(row).find("[name^='name']").val(); 
    var age = $(row).find("[name^='age']").val();           
    var sub1 = $(row).find("[name^='sub1']").val();         
    var sub2 = $(row).find("[name^='sub2']").val();         

    items.push({
        "name": name,
        "age": age,
        "sub1": sub1,
        "sub2", sub2
    });
});

var fileData = new FormData();

This is good

fileData.append('cust_first_name', $("[name='cust_first_name']").val());

This is the point of concern

fileData.append('items', items);

This is good

fileData.append('image1', $("[name='image1']").prop('files')[0]);

$.ajax({
    url: "myurl.php",
    cache: false,
    contentType: false,
    processData: false,
    data: fileData,
    type: 'post',
    success: function (response) {

    }
});

Below is the PHP code.

//$data = json_decode(file_get_contents('php://input'), true);

This is good

$cust_first_name = $_POST["cust_first_name"];

This is the point of concern as it shows [object, object]

$items = $_POST["items"];

foreach($items as $item) {
    echo "<pre>";
    print_r($item);
    echo "</pre>";  
}

This is good

if(isset($_FILES["image1"])) {

}
vivek_23 :

To pass javascript objects to the backend, you will have to JSON.stringify them to pass them over the network(like serialization).

So change fileData.append('items', items); to

for(var i=0;i<items.length;++i){
   fileData.append('items[]', JSON.stringify(items[i]));
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=350688&siteId=1