How to pass multiple arrays to page in PHP

1

$scope.items = [];

dados = $('#meu_form').serialize();

I would like to know: how to send / receive / read the above arrays to a page in PHP?

JavaScript:

    app = angular.module("app",[]);
    app.controller("controlador", ["$scope", "$http",

    function($scope, $http){
    $scope.items = [];

    $scope.submitForm = function() {
        var dados = $('#meu_form').serialize();

        $http({
          method  : 'POST',
          url     : 'pagina.php',
          data    :
          headers : {'Content-Type': 'application/x-www-form-urlencoded'} 
         })

    };

page.php

$dados = json_decode(file_get_contents('php://input'), true);

foreach ($dados as $key => &$value) {
    $codigo     = $value['codigo'];
    $quantidade = (float)$value['quantidade'];
    $v_total    = $value['v_total'];

}

$nome  = $_POST['nome'];
$email = $_POST['email'];
    
asked by anonymous 05.01.2017 / 01:27

1 answer

2

In JS , you simply mount another array with these arrays , in the field of data of $http , like this:

app = angular.module("app",[]);
app.controller("controlador", ["$scope", "$http",

function($scope, $http){
$scope.items = [];

$scope.submitForm = function() {
    var dados = $('#meu_form').serialize();

    $http({
      method  : 'POST',
      url     : 'pagina.php',
      data    : {scope: $scope.items, dados: dados}
      headers : {'Content-Type': 'application/x-www-form-urlencoded'} 
     })

};

And in PHP , you can get the values like this:

<?php 

// transforma o JSON enviado em array associativo
$dados = json_decode(file_get_contents('php://input'), true); 

$p = $dados['dados']; // pega o formulário serializado do AJAX 
parse_str($p, $dados['dados']); // tranforma em array de PHP 

?>

In this way, it follows the identification legend of the variables:

  • $dados['scope'] - would be equal to $scope.items .
  • $dados['dados'] - would be equal to $('#meu_form').serialize() , already in array.

To access a form field, such as input email , you will use:

$dados['dados']['email']

Now to access a email field of an element in scope , it will be:

$dados['scope'][0]['email']

If you want to go through all elements of your scope , it will be:

foreach($dados['scope'] as $item) {
    echo '<br>Nome: '  .  $item['nome'];
    echo '<br>Email: ' .  $item['email'];
}

Therefore, $item['email'] would equal $dados['scope'][X]['email'] , where X is the element currently covered by foreach .

    
05.01.2017 / 04:04