Martin
Martin

Reputation: 27

How to decode JSON into PHP Array/Variables

I'm pretty new at PHP and can't understand couple of things with this language about taking the data from POST request to PHP. Here is my little description about my code and the problem:

I have some serialized array that it's converted into JSON and needs to be sent via ajax to PHP, so I can use this values from the array to insert them into the DB.

Here is my code:

Validation function where I'm getting only the values from all validated forms (filled forms) because some of them can be empty on purpose. I'm encoding this forms with .serializeArray() and then I'm converting them into JSON because at the end of this function I need to return one array so I can use it in ajax POST.

// Validate forms
function validateForms() {
var formData = [];

$('#add-items form').each(function () {
    var itemFormId = $(this).attr('id');

    if ($(this)[0].checkValidity() == false) {
        console.log("Empty forms: " + itemFormId);
    } else {
        console.log("Filled forms: " + itemFormId + "\n");       
        var formDataX = $(this).serializeArray();

        switch (itemFormId) {
            case 'equippable-item-form':
                formDataX.push({name: 'item-type', value: "equippable"});
                break;
            case 'weapon-form':
                formDataX.push({name: 'equippable-item-type', value: "weapon"});
                break;
            case 'armor-form':
                formDataX.push({name: 'equippable-item-type', value: "armor"});
                break;
        }
        formData.push(...formDataX);
    }
});

formData = JSON.stringify(formData);
console.log(formData);
return formData;
}

Here is the ajax POST in short version:

formData = validateForms();
$.ajax({
    type: 'POST',
    url: 'php/admin.php',
    data: { items_data: formData },   
    success: function (data) {
         data = $.parseJSON(data);
         $("#status-message").text(data.message);
    },
 });

PHP code where I'm getting this POST and trying to decode this JSON:

if (isset($_POST['items_data'])) {
    $data = json_decode(stripslashes($_POST['items_data']),true);
    $status = testNewItem($data['item-name-input'], $data['price-input'], $data['item-level-input'], $data['required-level-input']);
}

// Print the status
if ($status):
    echo json_encode(["message" => $status]);
endif;

This is the code in my database.php where i'm inserting the values into the database:

function testNewItem($itemName, $price, $itemLevel, $reqLevel)
{
    $conn = connection();
    $conn->query("INSERT INTO item (`name`, `price`, `item_level`, `required_level`) VALUES ('" . $itemName . "', $price, $itemLevel, $reqLevel)");
    $conn->errorInfo();

    $status = "Successfully inserted new item into the database!";

    return $status;
    $conn = null;
}

Short version of my JSON:

[{
    "name": "item-name-input",
    "value": "asdasd"
}, {
    "name": "price-input",
    "value": "2"
}, {
    "name": "item-level-input",
    "value": "4"
}, {
    "name": "required-level-input",
    "value": "2"
}]

PROBLEM: I don't know if I'm decoding this JSON array properly, but I can't print it after successful POST. Also I don't know how to pass this values from $data into the function called testNewItem that supposed to insert this values into the database (This function works correctly if I put manually fixed values). I tried so many solutions that I found here on stackoverflow but can't find where I'm doing it wrong.

If anyone can help me, I would be very thankful.

Upvotes: 0

Views: 91

Answers (2)

Philipp
Philipp

Reputation: 15629

Currently your json has an structure like this

Array
(
    [0] => Array
        (
            [name] => item-name-input
            [value] => asdasd
        )

    [1] => Array
        (
            [name] => price-input
            [value] => 2
        )

    [2] => Array
        (
            [name] => item-level-input
            [value] => 4
        )

    [3] => Array
        (
            [name] => required-level-input
            [value] => 2
        )

)

to access it the way like you want to do it, you have to transform the json array to a key value format. This could be done like this

$json_data = json_decode(stripslashes($_POST['items_data']),true);
$data = [];
foreach ($json_data as $item) {
    $data[$item['name']] = $item['value'];
}

or if you don't want to use an loop

$data = array_combine(
    array_column($data, 'name'),
    array_column($data, 'value'));

Upvotes: 1

entity53
entity53

Reputation: 21

Your json is being converted into an array with more arrays beneath it.

You are trying to access it with $data, but you'd need to do $data[0] to access the first array.

$data[0]['name'] = item-name-input

Upvotes: 0

Related Questions