How to list array values (Angularjs) using PHP?

Asked

Viewed 297 times

0

I would like to know how to do the listing ("foreach") of my array $scope.items within PHP, so I can work individually with each entered value.

Javascript:

var app = angular.module('app', []);
app.controller('controlador', function($scope, $http) {
$scope.user = {};
$scope.items = [];
$scope.submitForm = function() {

    $http({
      method  : 'POST',
      url     : 'clone.php',
      data    : $scope.user,
      headers : {'Content-Type': 'application/x-www-form-urlencoded'} 
     })
      .success(function(data) {
        if (data.errors) {
          $scope.erroNome = data.errors.nome;
          $scope.erroEmail = data.errors.email;
        } else {
          $scope.mensagem = data.mensagem;
        }
      });
};

$scope.addItem = function (user){
        $scope.items.push({
            nome: $("input[name='nome']").val(),
            email: $("input[name='email']").val()
        });
      user.nome = '';
      user.email = '';  
};
});

HTML:

<body ng-app="app" ng-controller="controlador">

<form ng-submit="submitForm()">
    <input type="text" name="nome" ng-model="user.nome">
    <span ng-show="erroNome">{{erroNome}}</span>
    <input type="text" name="email" ng-model="user.email">
    <span ng-show="erroEmail">{{erroEmail}}</span>
    <input type="button" value="Adicionar" ng-click="addItem(user)" />
    <input type="submit" value="Enviar" />
</form>
<br />

<div ng-repeat="item in items">
Nome: {{item.nome}}<br />
E-mail: {{item.email}}
</div>

</body>

clone php.:

<?php
$errors = array();
$data = array();

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

if (empty($_POST['email']))
  $errors['email'] = 'E-mail obrigatório.';
else
  $errors['email'] = '';

if (empty($_POST['nome']))
  $errors['nome'] = 'Nome é obrigatório.';
else
  $errors['nome'] = '';

if (!empty($errors)) {
  $data['errors']  = $errors;
}
else {
  $data['mensagem'] = 'Os dados do formulário estão sendo enviados para "clone.php"!';
}

echo json_encode($data);
?>
  • You should not pass items? data :$scope.items

  • 1

    You’ll have to pass the items too, that way it stays like this: data: {user: $scope.user, items: $scope.items}. There in PHP you get like this: $email = $_POST['user']['email'] and $item = $_POST['item'][0]['nome']

  • What will be displayed on $email = $_POST['user']['email']?

2 answers

1


If you want to pass an array, you should use the model items and not user:

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

Then just read the array in PHP:

$post = file_get_contents("php://input");
$values = json_decode($post, true);

And then use a foreach:

foreach ($values as $key => &$value) {
   //$value tem o valor de cada item
}

0

Dynamic size array insertion into Mysql database and response complement:

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

$sql = "INSERT INTO teste(nome, email) VALUES (:nome, :email)";

try{
    $query= $conecta->prepare($sql);
    foreach ($_POST as $key => &$value) {
        $query->bindValue(':nome',$value['nome'],PDO::PARAM_STR);
        $query->bindValue(':email',$value['email'],PDO::PARAM_STR);
        $query->execute();
    }
}
.
.
.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.