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
– Ricardo Pontual
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']
– JuniorNunes
What will be displayed on
$email = $_POST['user']['email']
?– lucasbento