elclanrs
elclanrs

Reputation: 94101

Pass jQuery object array to PHP with JSON

How can I access the "code" and "type" values in PHP once I passed the array?
BTW, I'm using the "jquery-json" plugin. Is there any way to do this without any plugins?

jQuery:

$(function(){

    function product(code, type) {

        return {
            code: code,
            type: type
        }

    }

    var products = [];

    products.push(product("333", "Product one"), product("444", "Second product"));

    var jsonProducts = $.toJSON(products); 

    $.post(
        "php/process.php",
        {products: jsonProducts},
        function(data){
            $("#result").html(data);
        }
    );


});

PHP:

<?php 

$products = json_decode($_POST["products"], true);

foreach ($products as $product){
    echo $product;
}

?>

Upvotes: 2

Views: 9660

Answers (2)

Kevin Peno
Kevin Peno

Reputation: 9196

Each of your array offsets is a basic object.

foreach ($products as $product)
{
    echo $product->code;
    echo $product->type;
}

I'd suggest that you re-read the examples on json_decode to get a better understanding on how PHP translates JSON to PHP types

Upvotes: 2

Bleaourgh
Bleaourgh

Reputation: 1316

You should be able to just do $product->code and $product->type in your foreach loop.

By the way, if you want to print an array structure to check the formatting, you can use print_r.

Upvotes: 0

Related Questions