Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

js json.stringify to PHP json_decode

Tags:

json

jquery

php

I am new to JSON.

In JS, I create an array of values like so:

var arrFields = $("td>.frmInput").map(function(){
    return  {
        id: this.id,
        value: $(this).val()
    };
}).get();

I then AJAX them to the server like so:

$.ajax({
    type: "POST",
    url: "ajax/ax_all_ajax_fns.php",
    data: "Fields=" +JSON.stringify(arrFields),
    success: function(recd) {
        alert(recd);
    }
});

Note that there is a mixture of strings, plus the JSON.stringified (?) array. (There are additional string values sent, so data must remain as string.)

On the PHP side, I need to turn the received Fields string into an associative array.

Doing this:

$jsonAsStr_Fields = $_POST['Fields'];
die($jsonAsStr_Fields);

Returns this text string in the alert():

[{"id":"rateDriver","value":"Jacques Villeneuve"},{"id":"rateCar","value":"Chev"}]

Doing this:

$arrFields = json_decode($jsonAsStr_Fields, TRUE);
$driver = $arrFields['rateDriver'];
$car = $arrFields['rateCar'];
$tire = $arrFields['rateTire'];
die('Driver: [' .$driver. '] Car: [' .$car. ']  Tire: [' .$tire. ']');

Returns this:

Driver: [ ]  Car: [ ]  Tire: [ ]

How can I turn the $jsonAsStr_Fields string into an assoc array, and thereby output the correct values to my alert?

like image 779
cssyphus Avatar asked Feb 22 '26 20:02

cssyphus


2 Answers

Do this instead for your creation of values:

var arrFields = {};
$("td>.frmInput").each(function(){
    arrFields[this.id] = $(this).val();
});

This will create an object, when JSON-stringified, that looks like this:

{"rateDriver":"Jacques Villeneuve", "rateCar":"Chev"}

Which seems to be the format you want to use in your PHP code.

like image 83
Sean Johnson Avatar answered Feb 25 '26 10:02

Sean Johnson


You have an array of associative arrays and your arrays don't have the specified props, rateDriver for example is the value of the first array's element's id:

$driver = $arrFields[0]['id'];
$car = $arrFields[1]['id'];

For seeing the array's contents you use the famous var_dump function.

like image 22
undefined Avatar answered Feb 25 '26 09:02

undefined