Search code examples
javascriptphpjqueryajaxhttp-request-parameters

$.post is changing array of objects to array of arrays


I try to post via ajax some data. Watch sreenshot1. But jQuery automatic converts object to array. This can be seen in screenshot2 (chrome developer tools).

Data send to $.post:

enter image description here

Data inspect in chrome developer tools:

enter image description here

Edited:

Problems appear in PHP where I expect for Data property to be array of objects:

enter image description here

I want to read data like this:

foreach ($_POST["Data"] as $field)
{
    if ($field->Field == "username")
    {
            ...
    }
}

Solution

  • It's not really well spelled out in the PHP docs, but this is how it's supposed to work. For instance, the page on request variables has this to say about array-like cookies:

    If you wish to assign multiple values to a single cookie variable, you may assign it as an array. For example:

    <?php
      setcookie("MyCookie[foo]", 'Testing 1', time()+3600);
      setcookie("MyCookie[bar]", 'Testing 2', time()+3600);
    ?>
    

    That will create two separate cookies although MyCookie will now be a single array in your script. If you want to set just one cookie with multiple values, consider using serialize() or explode() on the value first.

    In other words, when you send in:

    FormData[0][Field]: username
    FormData[0][Value]: test3
    

    PHP interprets this as an array of arrays, which looks like this:

    array(1) {
      [0]=> array(2) {
        ['Field'] => String(8) "username",
        ['Value'] => String(5) "test3"
      }
    }
    

    And you can parse it like so:

    foreach ($_POST["Data"] as $field)
    {
        if ($field['Field'] == "username")
        {
                ...
        }
    }
    

    Bear in mind that a PHP array is actually an ordered map. In other words, its perfectly suited for storing the key => value data you're passing in with your POST.

    You seem to be expecting $_POST to contain simple objects (aka stdClass) and it simply doesn't. Most SOAP helpers in PHP will give you simple object responses (which is a typical blending of behaviors from PHP). See this question for some ideas if you really want to translate every $_POST["Data"] field into an object. But that would be expensive and unnecessary.