Return php data to angularJS

1

Good evening guys.

I'm doing a CRUD with angular and php. I have already managed to register data in the database, but I can not get this data and display it in the html. I think it's the file, fetch.php, which is not right.

Follow the link from my git where the code is. link

Follow my search php.

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

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

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

$usuario = mysqli_query($con, "SELECT * FROM users");
header('Content-Type: application/json');
echo json_encode($usuario);

My angle:

$scope.carregarUsuarios = function () {
        $http.get("php/buscar.php").then(function (retorno){
            console.log(retorno.data);
            //$scope.usuarios = data;
        });
    };
    
asked by anonymous 10.09.2015 / 03:48

4 answers

0

I got it.

The problem is that I had my angle code as follows:

$scope.carregarUsuarios = function () {

}

When the right one is

var carregarUsuarios = function () {

}

And as I described above, my php had to look like this:

$usuario = mysqli_query($con, "SELECT * FROM users");

header('Content-Type: application/json');

$return = array();

while ($dados = mysqli_fetch_assoc($usuario)) {
    array_push($return, $dados);
}

echo json_encode($return);

Ready!

Thank you, nonetheless for your return.

    
10.09.2015 / 21:29
0

In the function below, you do not have the user variable, it will be undefined, when you use the Get service, you can only pass a "url" parameter, in case you are passing 2 Url parameters and one more. p>

$scope.carregarUsuarios = function () {
 $http.get("php/buscar.php", usuario)
}

The method would look as follows.

    $scope.carregarUsuarios = function () {
      $http.get("php/buscar.php").then(function(retorno){
          $scope.usuarios = retorno.data;
          });
     }
    
10.09.2015 / 04:49
0

Create a function to create the json file

function createJson($fileName, $data){
    // "a" representa que o arquivo é aberto para ser escrito
    $fp = fopen($fileName.".json", "a");
    // Escreve "exemplo de escrita" no bloco1.txt
    $escreve = fwrite($fp, json_encode($data));
    // Fecha o arquivo
    fclose($fp);
}

In the controller, change your existing function to the following code

var Controllers = angular.module('AppController', []);

Controllers.controller('ListCtrl',['$scope','$http', function ($scope, $http){    
    $http.get('http://localhost/json/arquivo_criado.json').success(function(data){  
        $scope.retorno = data;
        console.log(data);
    });  
}]);
    
10.09.2015 / 16:48
0

Actually your problem must be happening because you are NOT returning the search result as an array, but rather as a simple sql result, ie the angle will be able to read, but it would not be possible to transcribe to a ng- repeat (or other treatment), since you are creating an 'invalid' json object.

What you should do is create a php that can transcribe your result in the following format:

[
    {id:1,cliente:'nome do cliente 1',estado_civil:'solteiro'..},
    {id:2,cliente:'nome do cliente 2',estado_civil:'casado'..},
    {id:3,cliente:'nome do cliente 3',estado_civil:'viuvo'..},
    [.. etc ..]
]

For this you can use code similar to this:

function usuarios(){
    $data = array();
    $qry = sql("select * from users");
    $i=0;
    foreach($qry as $r) {
        foreach ($r as $j=>$k) {
            if(!is_int($j)){
                $data[$i][$j] = $k;
            }
        }
        $i++;
    }
    return json_encode($data);
}

I recommend caution when making this get, especially with regard to creating a json file. From the moment you write a new json and save it to the server, it will be available to anyone who can access your folder structure.

With the need for an sql to get the data, your application gets more secure.

In the part of your AngularJs, it is actually preferable that you use a function with var instead of $scope to obtain this data. For creating a new $ scope, you increase the possibility of errors, since it creates interaction with DOM and increases the need for AngularJs checks.

The only detail of this is that your php result will look like this:

data: [
    {id:1,cliente:'nome do cliente 1',estado_civil:'solteiro'..},
    {id:2,cliente:'nome do cliente 2',estado_civil:'casado'..},
    {id:3,cliente:'nome do cliente 3',estado_civil:'viuvo'..},
    [.. etc ..]
]

Then your code in AngularJs, should return the array DATA , thus:

var carregarUsuarios = function () {
    $http.get("php/buscar.php").then(function (retorno){
        $scope.usuarios = retorno.data;
    });
};

Notice the definition of $scope.usuarios , I say that I want to assign the 'return' and then call the 'array', that is, retorno.data .

Complementing still more, if you want to use multiple functions in php, just do the following:

//utilize a url da seguinte maneira
$http.get("php/buscar.php?action=carregarUsuarios")
//ou chamando outra função
$http.get("php/buscar.php?action=maisFuncao")

And the Php:

switch($_GET['action']) {
    case 'carregarUsuarios': carregarUsuarios();
    break;

    case 'maisFuncao': maisFuncao();
    break;
}

function carregarUsuarios() {
    //sua função aqui
}
function maisFuncao() {
    //sua função aqui
}
    
12.11.2015 / 10:40