Data registration with Angularjs and PHP does not work

Asked

Viewed 1,211 times

-1

Hello,

I have a form, simple, with 3 fields, name, email and password in HTML and along with an Angularjs code. However, when submitting the form, I get the message that the data sent to the bank, but they are not there in 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>
<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">
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.'));
}
?>
  • What it returns in the request answer?

  • For security reasons, use Prepared statements in queries, especially those involving strings, helping to deliver SQL Injection. What is the value of the variable $ins after the query? Does the PHP/Apache/Nginx error log have any error messages? Try enabling error display to get a better sense of what’s going on.

  • Ta very simple and visible the first problem, working or not

  • Sorry @Otto, how could I treat this?

  • @Viníciusgobboa.deOliveira, I don’t know how to use Prepared statement with mysqli. Can help me?

  • @Gustavosevero the way this in the answer

  • Well @Otto, I corrected the treatment. I put it in the post edition, check it out. And what happens is that only the code is inserted in the bank, that is, only the code field is filled, the other fields are blank... Very strange.

  • From what I’ve noticed, the problem is not in php but in Angular.

  • Note that in your angular include code is breaking.

  • Ready @Ivanferrer, include fixed. But here on my computer, there is no such break and yet, nothing.

  • Still broken... rrsrsrs, missing quotes

Show 6 more comments

3 answers

2

Check that no errors occurred in PHP at insertion time:

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!'));
  • I use this code and run php only in the url, @Cleberazevedo?

  • Well, I just ran php in the url, as I asked you and the message that appeared on the screen was this, @Cleberazevedo. "{"status":1,"msg":"Successful registration!"}"

  • @Gustavosevero, this method $http.post({...}) the correct would not be $http({...}) ? you can use an equivalent: jQuery.post({...})or $.post({...}). Just don’t forget to insert the jquery library.

  • So the problem is not in inserting with php, make sure you are passing the ng parameters correctly?

  • Did you use mysqli_error($ins) ? It will return you if there was an error in the PHP query

  • @Ivanferrer, I’m sure it’s not because in the Angular documentation it shows how I put it. Check the link: [https://docs.angularjs.org/api/ng/service/$http]

  • Ah, okay, I wasn’t sure about that, but the exit wouldn’t have to be something like that: parse_str(file_get_contents("php://input"),$putData); is that I’m more used to defining the post as object value:$http({&#xA; headers: {'Content-Type': 'application/json'},&#xA; url: 'url.php', method: 'POST', data: $.param({param: param}) });

  • Here is an explanation of the problem of using $http.post(), in English, but I think I can understand: http://stackoverflow.com/questions/19254029/angularjs-http-post-does-not-send-data

  • @Ivanferrer, do you have any more hints, hint?

  • I’ll try to give you an answer, but I won’t test it, you tell me if it worked blz.

Show 5 more comments

1

As you use ng-Ubmit on a specific location you can repurpose and summarize the code even in ng-model, I will pass on my way to create <form> with ng-submit with angular 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>
<body ng-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");
}

?>

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>
<script type="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 don’t remember whether it’s array or object, I treated for both cases, but you can give one var_dump($_POST); die(); to see the way out, but I think it’s something like that:

<?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.'));
}
?>
  • Only one thing @Ivanferrer, if I only run php, the user variable will be empty. And if I run with HTML, the result of var_dump will not appear, you know it, right?

  • Your HTML code, it seems that neither submit the data did not submit, because nothing appeared in the console.

  • Of course it appears @Gustavosevero, just you run in the Chrome console, in the network tab, select the option All and click the file executed, will appear the array.

  • If you find it difficult you can use a site like this: http://resttest.com/

  • Or that extension of Chrome: https://chrome.google.com/webstore/detail/advanced-rest-client/hgmloofddffdnphfgcellkdfbfbjeloo

Browser other questions tagged

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