Error passing PHP Array to Angularjs by JSON

Asked

Viewed 343 times

2

I am in doubt in a code that I am developing, I am passing a query in the Mysql database and I need this answer to return in JSON for Angularjs to understand and write in HTML.

Follows the code:

<?php 

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

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

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

    $userid = $myData['userid'];

    $sql = "SELECT * FROM `usuario` WHERE id_usuario = '$userid'";

    $user = $conn->query($sql) or die("[Protocolo] = #8");

    $rowarray = array();

    $rows = array();

    while($linha = $user->fetch_assoc()) {

        $row['id_usuario'] = $linha['id_usuario'];
        $row['user_nome'] = $linha['user_nome'];
        $row['user_cpf'] = $linha['user_cpf'];
        $row['user_cnh'] = $linha['user_cnh'];
        $row['user_rg'] = $linha['user_rg'];
        $row['user_address'] = $linha['user_address'];
        $row['user_bairro'] = $linha['user_bairro'];
        $row['user_contato'] = $linha['user_contato'];
        $row['user_dt_nascimento'] = $linha['user_dt_nascimento'];
        $row['id_cidade'] = $linha['id_cidade'];
        $row['user_nv_acesso'] = $linha['user_nv_acesso'];

        array_push($rows, $row);
    }

    $dados['userupdate'] = $rows;

    array_push($rowarray, $dados);

    echo json_encode($rowarray);

    $conn->close();
?>

When I see the POST DATA in Angularjs returns

200 - [Object Object]

But when I duplicate echo that way:

echo json_encode($rowarray); echo json_encode($data);

The Output on the console comes out like this:

200 - [{"userupdate":[{"id_usuario":"10","user_name":"student","user_cpf":"1234","user_cnh":"1234","user_rg":"1234","user_address":"Street 66, Block K49, Lot 23","user_bairro":"Independ\u00eancia","user_contato":"6294131510","user_dt_nascimento":"1996-02-05","id_cidade":"150140","user_nv_acesso":"1"}]}]{"userupdate":[{"id_usuario":"10","user_nome":"aluno","user_cpf":"1234","user_cnh":"1234","user_rg":"1234","user_address":"Rua 66, Block K49, Lot 23","user_bairro":"Independ\u00eancia","user_contato":"6294131510","user_dt_nascimento":"1996-02-05","id_cidade":"150140","user_nv_acesso":"1"}]}

Consulting 2 times, who can help I am grateful.


Edit:

Below is the app.js that sends the data to PHP and returns by echo JSON:

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

    $scope.edituser = function(obj) {

    var iduser = (obj.target.attributes.data.value);

    $scope.userid = iduser;

        var formData = { 
            'userid' : $scope.userid
        };

        var postData = 'myData='+JSON.stringify(formData);

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

        request.success(function (data, status, headers, config) {
            $scope.success = true;
            console.log(status + ' - ' + data); //Captura de Dados


        });
        request.error(function (data, status, headers, config) {
            $scope.error = true;
            console.log(error);
        });


    }
}]);

2 answers

1


I just removed redundancies and nonsense:

    <?php 

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

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

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

    $userid = $myData['userid'];

    $sql = "SELECT * FROM `usuario` WHERE id_usuario = '$userid'";

    $user = $conn->query($sql) or die("[Protocolo] = #8");

    while($linha = $user->fetch_assoc()) {

        $dados['userupdate'][]['id_usuario'] = $linha['id_usuario'];
        $dados['userupdate'][]['user_nome'] = $linha['user_nome'];
        $dados['userupdate'][]['user_cpf'] = $linha['user_cpf'];
        $dados['userupdate'][]['user_cnh'] = $linha['user_cnh'];
        $dados['userupdate'][]['user_rg'] = $linha['user_rg'];
        $dados['userupdate'][]['user_address'] = $linha['user_address'];
        $dados['userupdate'][]['user_bairro'] = $linha['user_bairro'];
        $dados['userupdate'][]['user_contato'] = $linha['user_contato'];
        $dados['userupdate'][]['user_dt_nascimento'] = $linha['user_dt_nascimento'];
        $dados['userupdate'][]['id_cidade'] = $linha['id_cidade'];
        $dados['userupdate'][]['user_nv_acesso'] = $linha['user_nv_acesso'];

    }

    $conn->close();

    echo json_encode($dados); exit;
?>

In this final stretch, inverti putting the $conn->close(); before echo json_encode(blablabla) and added an "Exit" to terminate any executions that might occur. Thus, it gives a greater assurance that the result in json will be printed without formatting issues.

Actually, the changes I posted don’t change anything. The problem in the original code is the mess with 3 arrays, use of array_push, etc. Unnecessary and very messy.

  • I understood, but then I think I’m wrong my app.js from Angularjs, I did the test but it returns 200 - [Object Object];

  • in the javascript script that reads the result of the json generated by php, make a console.log(variavel_que_recebeu_o_resultado).. I also think there is no mistake.. I think you are not able to read the received object. I think it’s best to post the snippet of the script you’re using to read the json.

  • I put the code of my app.js below the previous message, the intention is to return values requested from the Database so I change values written in HTML on the same page.

  • 1

    Now... need to parse for json format... console.log(status + ' - ' + angular.toJson(data));

  • Now I managed to capture the data, see the Console: 200 - {"userupdate":[{"id_usuario":"10"},{"user_nome":"aluno"},{"user_cpf":"1234"},{"user_cnh":"1234"},{"user_rg":"1234"},{"user_address":"Rua 66, Quadra K49, Lote 23"},{"user_bairro":"Independência"},{"user_contato":"6294131510"},{"user_dt_nascimento":"1996-02-05"},{"id_cidade":"150140"},{"user_nv_acesso":"1"}]}

1

There is an error in the generated JSON. In column 295, the collection is being incorrectly closed:

"user_nv_acesso":"1"}]}]{"userupdate"

When it really should be:

"user_nv_acesso":"1"}]},{"userupdate

Complementing with an array end token:

"id_cidade":"150140","user_nv_acesso":"1"}]}]

You can validate JSON content using online tools such as http://json.parser.online.fr/. Your original JSON appears like this:

inserir a descrição da imagem aqui

  • Well I think it’s wrong because it’s generating twice, but the idea is to only take the database query and relate for me to create $Scope in Angular and make it Type in HTML.

Browser other questions tagged

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