Return php data to Angularjs

Asked

Viewed 1,748 times

1

Good evening, everyone.

I’m doing a CRUD with angular and php. I’ve been able to register data in the database, but I’m not able to take this data and display it in html. I think it’s the file, fetch.php, that’s not right.

Follow the link to my git where the code is. https://github.com/GugaSevero/CRUD_AngularJS

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;
        });
    };
  • Pg_fetch_assoc would not be from Postgresql and not from MySQL in your vuscar.php file?

  • I don’t know @Giancarlogiulin, I took this code from another post of this American forum.

4 answers

0


got.

The problem is that I was with my angular code as follows:

$scope.carregarUsuarios = function () {

}

When the right thing 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!

I thank you, yet for your return.

0

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

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

the method would be as follows:.

    $scope.carregarUsuarios = function () {
      $http.get("php/buscar.php").then(function(retorno){
          $scope.usuarios = retorno.data;
          });
     }
  • I removed the user from Function, but still does not return the data. $Scope.loadUrswords = Function() { $http.get("php/buscar.php"). Success(Function(data){ $Scope.usuarios = data; }); };

  • First switch to Then instead of success, and check what’s returning within the return.data @Gustavosevero, and also check the return.status

  • i did what you suggested: $Scope.loadUsuarios = Function () { $http.get("php/buscar.php"). then(Function(return){ console.log(return.data); //$Scope.usuarios = data; }); }; E nothing appears on the console. OBS: How to put indented code, formatted, here?

  • here in the comment there is no way .. take pfv the return.status -> if it is 200 is all OK on the web and reamente problem is on the server side

  • i think the problem is in php. .

  • Nothing appears on the console... I made a console.log(return.status) and nothing.

  • I fixed my php... The data appears on the console, but I’m not getting it to appear on the screen. , I changed, fixed my php... The data is returned, I can see it on the console, but I can’t see it in html. $Scope.loadUsuarios = Function() { $http.get("php/buscar.php"). then(Function (data){ console.log(data); $Scope.usuarios = data; }); };

  • Already tried to display the object ? {{usuarios}}. You can create an alias pro controller: ng-controller="myCrudCtrl as Ctrl", and then call: Ctrl.usuarios

  • And from what I’m seeing, you’re wearing the json_encode() before creating the list and handling the output data. This output has no collection.

Show 4 more comments

0

Create a role 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);
    });  
}]);
  • I’ve changed, fixed my php... Data is returned, I can see it in the console, but I can’t display it in html. $Scope.loadUsuarios = Function() { $http.get("php/buscar.php"). then(Function(data){ console.log(data); $Scope.usuarios = data; }); };

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, that is, the angular will be able to read, but it would not be possible to transcribe to an 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 a 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 doing this get, especially when it comes to creating a json file. Once you write a new json and write 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 is safer.

In the part of your Angularjs, it is actually preferable that you use a function with var instead of $scope to get that data. By creating a new $Cope, you increase the possibility of errors, as it creates interaction with DOM and increases the need for Angularjs checks.

The only detail of this is that your php result will be 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 to the array DATA, being like this:

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

Note the definition of $scope.usuarios, i say I want to assign the 'return' and then call the 'array', ie, retorno.data.

Complementing even 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 Php:

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

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

function carregarUsuarios() {
    //sua função aqui
}
function maisFuncao() {
    //sua função aqui
}

Browser other questions tagged

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