Data register with AngularJS and PHP does not work

-1

Hello,

I have a form, simple, with 3 fields, name, email and password in HTML and along with an AngularJS code. However, by submitting the form, I get the message that the data was sent to the bank, but they are not there at the same.

<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>CRUD AngularJS</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js></script></head><bodyng-controller="MainCtrl as ctrl">
<form ng-submit="ctrl.submit()">
Nome<br>
<input type="text" ng-model="ctrl.user.nome"><br>
Email<br>
<input type="text" ng-model="ctrl.user.email"><br>
Senha<br>
<input type="password" ng-model="ctrl.user.senha"><br>
<input type="submit" id="submit" value="Submit" />
</form>

<script type="text/javascript">
angular.module('myApp', [])
    .controller('MainCtrl', ['$scope', '$http', function($scope, $http){
        $scope.list = [];
        var self = this;
        self.submit = function() {
          console.log('User clicked submit with ', self.user);
            $http.post('php/salvar.php', {'nome': $scope.nome, 'email': $scope.email, 'senha': $scope.senha})
            .then(function(response) {
                console.log(response.status);
                console.log(response.data.msg);

              }, function(response) {
                console.log(response.status);
                console.log(response.msg);

              });
        }
}]);
</script>
</body>
</html>

PHP:

?php
$user = 'root';
$password = 'root';
$db = 'angularDB';
$host = 'localhost';

$con = mysqli_connect("localhost", $user, $password, $db);

// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$nome = $_POST['nome']; 
$email = $_POST['email'];
$senha = $_POST['senha'];

$ins = mysqli_query($con, "INSERT INTO users VALUES (NULL, '$nome', '$email', '$senha')");

if($ins == 1){
echo json_encode( array('status' => 200, 'msg' => 'Cadastro efetuado com sucesso!'));
}else{
echo json_encode( array('status' => 0, 'msg' => 'Erro ao cadastrar no banco.'));
}
?>
    
asked by anonymous 27.08.2015 / 21:22

3 answers

1

Make sure there are no PHP errors at the time of insertion:

example:

if (mysqli_error($ins))
  echo json_encode( array('status' => 1, 'msg' => 'Ocorreu um problema'));
else
  echo json_encode( array('status' => 1, 'msg' => 'Cadastro efetuado com sucesso!'));
    
27.08.2015 / 21:33
0

First we have HTML with angular:

  <!DOCTYPE html>
    <html ng-app="myApp">
    <head>
    <title>CRUD AngularJS</title>

    </head>
    <body ng-controller="MainCtrl as ctrl">
    <form ng-submit="ctrl.submit()">
    Nome<br>
    <input type="text" ng-model="ctrl.user.nome"><br>
    Email<br>
    <input type="text" ng-model="ctrl.user.email"><br>
    Senha<br>
    <input type="password" ng-model="ctrl.user.senha"><br>
    <input type="submit" id="submit" value="Submit" />
    </form>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script><scripttype="text/javascript">
angular.module('myApp', [])
    .controller('MainCtrl', ['$scope', '$http', function($scope, $http){

        $scope.status = null;
        $scope.msg = null;
        $scope.user = {};

        $scope.$watch('user', function (newValue, oldValue) {
             if (newValue !== oldValue) {
                 $scope.post(newValue);
             }
        });

        $scope.post = function (user) {
            try {

                $http({
                    url: "php/salvar.php",
                    method: 'POST',
                    data: {'user': user}

                }).success(function (response) {
                    if (angular.isDefined(response.status)) {
                         console.log(response.status);
                        $scope.status = response.status;
                         console.log(response.msg);
                        $scope.msg = response.msg;
                    }

                });

            } catch (e) {
                console.log(e);
            }

        };

}]);
</script>
</body>
</html>

And in PHP, I do not remember if it's array or object, I've dealt for both cases, but you can give var_dump($_POST); die(); to see the output, but I think it's something like this:

<?php

$user = 'root';
$password = 'root';
$db = 'angularDB';
$host = 'localhost';

 $con = mysqli_connect("localhost", $user, $password, $db);

// Check connection
if (mysqli_connect_errno()) {
   echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

 $user = $_POST['user'];

if (is_array( $user)) {
 $nome = $user['nome']; 
 $email = $user['email'];
 $senha = $user['senha'];
} else {
 $nome = $user->nome; 
 $email = $user->email;
 $senha = $user->senha;
}

 $ins = mysqli_query($con, "INSERT INTO users VALUES (NULL, '$nome', '$email', '$senha')");

if ($ins) {
    json_encode(array('status' => 1, 'msg' => 'Cadastro efetuado com sucesso!'));
} else {
   echo json_encode( array('status' => 0, 'msg' => 'Erro ao cadastrar no banco.'));
}
?>
    
28.08.2015 / 19:34
0

As you use ng-submit on a specific location you can reuse and summarize the code even in ng-model, I'll get my way of creating <form> with ng-submit with angle based on what you need:

HTML

<!DOCTYPE html>
<html ng-app="myApp">
<head>
    <title>CRUD AngularJS</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script></head><bodyng-controller="MainCtrl">
    <form ng-submit="submit()">
        Nome<br>
            <input type="text" ng-model="nome"><br>
        Email<br>
            <input type="text" ng-model="email"><br>
        Senha<br>
            <input type="password" ng-model="senha"><br>
        <input type="submit" id="submit" value="Submit" />
    </form>
</body>
</html>

JS

var Myapp = angular.module('myApp',[]);

Myapp.controller('MainCtrl', ['$scope', '$http', function($scope, $http) {

    $scope.submit = function () {

        var formData = { 'nome' : $scope.nome, 'email' : $scope.email, 'senha' : $scope.senha };
        var postData = 'myData='+JSON.stringify(formData);

        var request = $http({
            method: "POST",
            url: './php/salvar.php',
            data: postData,
            headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }
        });

        request.success(function (data, status, headers, config) {
            $scope.success = true;
            console.log(status + ' - ' + data); //Captura de Dados
            if ( data.trim() === '[Protocolo] = #1') {
              alert("[INFO]: Cadastro efetuado com sucesso! ");
            }
            if ( data.trim() === '[Protocolo] = #2') {
              alert("[INFO]: Erro ao cadastrar no banco. ");
            }
        });
        request.error(function (data, status, headers, config) {
            $scope.error = true;
            console.log(error);
        });
    }
}]);

PHP

<?php

$user = 'root';
$password = 'root';
$db = 'angularDB';
$host = 'localhost';

$con = mysqli_connect("localhost", $user, $password, $db);

// Check connection
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

header('Content-Type:text/html;charset=UTF-8');

    include("../class/conexao.class.php");

    $myData = json_decode($_POST['myData'], true);

$nome = $myData['nome'];
$email = $myData['email'];
$senha = $myData['senha'];

$ins = mysqli_query($con, "INSERT INTO users VALUES (NULL, '$nome', '$email', '$senha')");

if($ins == 1) {
    echo ("[Protocolo] = #1");
} else {
    echo ("[Protocolo] = #2");
}

?>
    
07.12.2015 / 00:38