Ahmad
Ahmad

Reputation: 12737

why does PHP json_encode ignore empty arrays?

I have the following javascript that sends data to a PHP function:

<script>
    var mydata = {
                   id:123,
                   name: 'mike',
                   orders: []
    };

    $.ajax({
       type: 'POST',
       url:  'test.php',
       data: {save_data:mydata},
       success: function(data) {
                   alert('php received: ' + data);
       }
    });
</script>

and my test.php file contains the following code:

<?php
     if (isset($_POST['save_data'])) {
          $json = json_encode($_POST['save_data']);
          echo $json;     // just to check what has been received
          exit();
     }
?>

What I expect to received from PHP is: {"id":"123","name":"mike","orders":"[]"}

What I got back is {"id":"123","name":"mike"}

Notice that orders array has been eliminated from the output. No place holder for it. I tried adding some dummy elements in the array, and that worked fine, and I received the array back with the elements.

I need PHP to receive the json object as is, even if it contains empty arrays.

How can I do that?

Upvotes: 3

Views: 1532

Answers (2)

Vo Kim Nguyen
Vo Kim Nguyen

Reputation: 1633

It is not error of PHP. It cause by Jquery will igrone empty array when send it to server. So you have to parse array in 'orders' key to string JSON before send

var mydata = {
               id:123,
               name: 'mike',
               orders: []
};

Change to

var mydata = {
               id:123,
               name: 'mike',
               orders: JSON.stringify([])
};

Upvotes: 0

Quentin
Quentin

Reputation: 944159

The JSON object is created inside PHP. Before then you just have form data.

jQuery will encode form data in a PHP-friendly style.

If you give it:

data: { foo: [1, 2, 3] }

It will convert that to:

foo[]=1&foo[]=2&foo[]=3

(although it will percent encode the [])

You get a key=value pair for each value.

If you have an empty array then you don't have any values, so you don't get any key=value pairs.

There is no way to encode "an empty array" using PHP's extensions to the form url encoding syntax.


You have two basic options:

  1. Tell PHP about what data structure you want to create in advance and have it fill in the empty arrays.
  2. Generate the JSON on the client

Upvotes: 2

Related Questions