1

How can I send a nested object via POST request?

var name = "test",
    path = "?diffCurr%5B%5D=FALSE&diffProv%5B%5D=FALSE",
    data = {
        datatype:"report",
        "value":{
                "name":name,
                "query":path
            }
        };

    $.ajax({
        type:"POST",
        url: "resources/savedata.html",
        data: data,
        success: function(data){
                    ...
        },
        complete: function(){
                    ...
        }
    })

When I check in the chrome, in the network tab under "form data", I see this:

datatype:report
value[name]:test
value[query]:?diffCurr%5B%5D=FALSE&diffProv%5B%5D=FALSE

Basically, I was expecting $_POST["value"] to contain an object with name and query.

Michele
  • 8,563
  • 6
  • 45
  • 72
  • POSTs by default in PHP just work as key-value pairs. If you want more functionality from them, you'll have to implement that yourself or find a library that's already done that. I would say it looks like the data is being sent and received properly. – Adam Mar 27 '14 at 20:05

2 Answers2

1

Basically, I was expecting $_POST["value"] to contain an object with name and query.

It does.

You are just looking at the raw data which is encoded in application/x-www-form-urlencoded with PHP's square bracket syntax for complex objects.

When PHP deserializes it to populate $_POST, it will do so in the form you expect.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Thank you. I'm actually not using PHP, but something inspired to it. I wanted to make sure I haven't to do anything on the client side. – Michele Mar 28 '14 at 06:30
1

One of the easiest way is serializing in a Json string your nested object

 $.ajax({
    type:"POST",
    url: "resources/savedata.html",

    data: JSON.stringify(data),

    success: function(data){
                ...
    },
    complete: function(){
                ...
    }
Matteo
  • 1,654
  • 17
  • 24