Home > Software design >  How can I access jquery Stringified array elements using PHP?
How can I access jquery Stringified array elements using PHP?

Time:12-03

I use the following to post to a PHP page, showing the result in the message div:

        let x = JSON.stringify($('#my-form').serializeArray());
        $.post("processjs.php", {data:x})

         .done(function(result, status, xhr) {
            $("#message").html(result)
          })

That results in the following array:

[{"name":"AccountName","value":"TestAcct"},{"name":"AccountID","value":"FR-62"},{"name":"Domain","value":"TestDomain"},{"name":"Status","value":"Enabled"},{"name":"ConfigurationSetName","value":"WLOD-1"},{"name":"SecConfVersion","value":"4"},{"name":"LastUpdated","value":"2022-12-1"},{"name":"MostCurrentVersion","value":"Yes"},{"name":"NotCurrentVersionReason","value":"None"},{"name":"RouterCount","value":"3"},{"name":"CustomerASN","value":"999999"},{"name":"ConfiguredP","value":"127"},{"name":"IPInstalled","value":"No"},{"name":"SharedGroup","value":"True"},{"name":"overlap","value":"False"},{"name":"POverlap","value":"False"},{"name":"ACLSDConfigured","value":"No"},{"name":"ACESDCount","value":"432"}]

How can I use PHP to access the array elements? Why are all of the keys and values prefaced with "name:" or "value:"?

I have tried using the following to access a key:

$json = json_decode(stripslashes($_POST['data']),true);
$AccountName = $json['AccountName'];
echo $AccountName;

But I always get the same message:

Undefined array key "AccountName"

I have tried using the following to access a key:

$json = json_decode(stripslashes($_POST['data']),true);
$AccountName = $json['AccountName'];
echo $AccountName;

I have also tried things like

$AccountName = $json[0]['AccountName'];
 or
$AccountName = $json[0];
 and also
$AccountName = $json[1];

CodePudding user response:

In your sample request, AccountName is not a index, it is value of name index in a object inside a array.

Please try like this.

$json = json_decode(stripslashes($_POST['data']),true);
foreach($json as $inner){
    $name = $inner['name']; //"AccountName" ....  Here you will get value in $name a name .
    $accountId = $inner['value']; //"TestAcct"   ...  Here you will get value in $accountId as "TestAcct" name .
}

Outputs are stated only for first iteration of foreach .

  • Related