Edu Arif
Edu Arif

Reputation: 123

How to Post Array multidimensional angular js

I have an array in angularjs, Example as below.

$scope.order.qty='20';
$scope.order.adress='Bekasi';
$scope.order.city='Bekasi';

This array can post with this code

$http({
          method  : 'POST',
          url     : '<?php echo base_url(); ?>add_order',
         data    : $scope.order,
          headers : {'Content-Type': 'application/x-www-form-urlencoded'} 
         })

I can get all variable with

$_POST = json_decode(file_get_contents('php://input'), true);
$_POST['qty'];
$_POST['address'];
$_POST['city'];

But I'm confused if array multi-dimensional like this :

$scope.items[1].kode_produk='PR_1';
$scope.items[2].kode_produk='PR_2';
$scope.items[3].kode_produk='PR_3';

How to post and get variable from array multi-dimensional like this ?

Upvotes: 2

Views: 739

Answers (3)

SpazzMarticus
SpazzMarticus

Reputation: 1277

Your json will look like this if you send $scope.items :

[
  {
    "kode_produk": "PR_1"
  },
  {
    "kode_produk": "PR_2"
  },
  {
    "kode_produk": "PR_3"
  }
]

Which results to this php array after $input = json_decode(...):

array (size=3)
  0 => 
    object(stdClass)[1]
      public 'kode_produk' => string 'PR_1' (length=4)
  1 => 
    object(stdClass)[2]
      public 'kode_produk' => string 'PR_2' (length=4)
  2 => 
    object(stdClass)[3]
      public 'kode_produk' => string 'PR_3' (length=4)

You have an array of objects, not a multidimensional-array!

You can iterate over the items like:

foreach($input as $item)
{
    echo $item->kode_produk;
}

Upvotes: 1

Marcin Dargacz
Marcin Dargacz

Reputation: 146

Is one way

in JavaScript send data $scope.items, for example:

$http({
          method  : 'POST',
          url     : '<?php echo base_url(); ?>add_order',
         data    : $scope.items,
          headers : {'Content-Type': 'application/x-www-form-urlencoded'} 
         })

and on the site PHP code write:

$_POST = json_decode(file_get_contents('php://input'), true);
var_dump($_POST); die();

and analyze the data structure.

Upvotes: 0

Yrysbek Tilekbekov
Yrysbek Tilekbekov

Reputation: 2875

You can pass array like it:

$http({
      method  : 'POST',
      data    : { items: $scope.items }
      ...
     })

getting data:

$_POST = json_decode(file_get_contents('php://input'), true);
$items = $_POST['items'];

Upvotes: 1

Related Questions