Syntax error warning in the console running Angularjs

Asked

Viewed 125 times

0

I have the following code, which uses Factory:

angular.module("fluxo", ["ngRoute"]);

.factory('factCliente', ['$http', function($http) {
var _getData2 = function(id_empresa) {
    return $http.post("php/index.php", id_empresa);
};

return {
    getData2: _getData2
}
}])

.controller("fluxoCtrl", function ($scope, $http, factCliente) {

//var id_empresa = {id: id_empresa};
var id_empresa = {id: 1};
factCliente.getData2(id_empresa).then(function(response) {
    $scope.mostraTodasContasEntradas = response;
}, function(error) {
    console.log("Ocorreu um erro: " + error);
});
});

And the warning that appears on the console, is this:

"SyntaxError: Unexpected token ["

Php code:

<?php
    function mostraContasEntrada($id_empresa){
    header('Content-Type: application/json');
    $pdo = conectar();
    $this->mostraDadosEntrada=$pdo->prepare(
        "SELECT c.categoria, sc.subcategoria, data, valor 
         FROM entrada e 
         JOIN cat_entradas c 
         on c.id_categoria = e.categoria 
         JOIN sub_cat_entrada sc 
         on sc.id_subcategoria 
         WHERE id_empresa=:id_empresa 
         ORDER BY data DESC");
    $this->mostraDadosEntrada->bindValue(":id_empresa", $id_empresa);
    $this->mostraDadosEntrada->execute();

    $return = array();

    while ($r = $this->mostraDadosEntrada->fetch(PDO::FETCH_ASSOC)) {
        $dataP = explode("-", $r['data']);
        $data = $dataP[2].'/'.$dataP[1].'/'.$dataP[0];

        $r['data'] = $data;
        $r['valor'] = number_format($r['valor'],2,',','.');
        $r['subcategoria'] = utf8_encode($r['subcategoria']);
        $return[] = $r;

        //echo $data.'  '.$r['categoria'].'  '.utf8_encode($r['subcategoria']).'  '.number_format($r['valor'],2,',','.')."<br>";

        echo json_encode($return);
    }

    }
<?

Class and function call:

require_once "../con/conexao.php";
require_once "../classes/contaEntrada.php";
require_once "../classes/contaSaida.php";

$entrada = new contaEntrada();
$saidas = new contaSaida();

$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$id_empresa = $request->id_empresa;

$entrada->mostraContasEntrada($id_empresa);

Does anyone know what problem, what syntax error, is this?

  • Post the complete error, but still check the key locks and parentheses. Initially it has a bracket "[" opening in a wrong place. Make good use of indentation and call angular module again when you can.

  • As the console says it is syntax error. If you have any idea where the error occurs, you can thresh the code by the browser.

  • I’ve looked for another clasp that might be open and not closed, but I can’t find it. you can search yourself, because all my code is, here, in the post.

  • 1

    Your JSON return may be invalid, as pointed out by the exception in the console. You can post an example?

  • I put the code here.

  • A few things I noticed analyzing your code. Your PHP has some syntax errors, such as closing the tag <? whereas it should be ?> and some clasps out of place. I recommend to check the closure of everything, because an error in php can cancel all your javascript, even without running the function directly. Another thing, put one on console.log(mostraTodasContasEntradas) At the end of your controller to see what php is returning, sometimes it is a php logic error and not Angularjs. Always search for a debug of the console results to understand the problem. = D

  • @Celsomtrindade, only here I put the closing of the php tag. In my code same, I did not put.

  • var id_empresa = {id: id_empresa} This value, it comes from where? And is being generated as?

  • Celso, I put the console.log(displayTodasContasEntrate) and this came up: (id_company) { console.log('company id '+id_enterprise); $http.get("php/index.php? action=showConnect(id_enterprise)"). then( Function(date) { $Scope.accounts = date; //console.lo...

  • @Celsomtrindade, actually I’m putting this id_company in hand, because I didn’t create Ssion, I’m just testing.

  • If you use the console, as I said, what result will you get? Not the error that appears directly on the console, but the return you call by inserting the console.log into the controller. So let’s know if json is coming with error or not. I believe the problem is your php return

Show 6 more comments

2 answers

3


The error occurs because the $http post. return a file and not the data itself. To access the return you need to pass two methods to another that is in the called file then. The first method receives the data itself. The second method receives an error object if it has happened.

To illustrate:

The variable shows All shopsConnect must be used in part of your code to display a certain list? In your code it is receiving a file and not an array structure. See the corrected example below and note this part: factCliente.getData2(id_empresa). then

angular.module("fluxo", ["ngRoute"]);

angular.module("fluxo").config(function ($routeProvider) {
    $routeProvider.when("/entradas", {
        templateUrl: "views/entradas.html",
        controller: "fluxoCtrl"
    })
    .when("/saidas", {
        templateUrl: "views/saidas.html",
        controller: "fluxoCtrl"
    })
    .otherwise({redirectTo: "/index"});
})

.factory('factCliente', ['$http', function($http) {
    var _getData2 = function(id_empresa) {
        return $http.post("php/index.php", id_empresa);
    };

    return {
        getData2: _getData2
    }
}])

.controller("fluxoCtrl", function ($scope, $http, factCliente) {
    var id_empresa = {id: id_empresa};
    factCliente.getData2(id_empresa).then(function(response) {
        $scope.mostraTodasContasEntradas = response;
    }, function(error) {
        console.log("Ocorreu um erro: " + error);
    });
});
  • Please avoid long discussions in the comments; your talk was moved to the chat

2

I changed the part

return {
    getData2: _getData2,
}

for

return {
    getData2: _getData2
};

I removed the last comma and added a semicolon. Jslint passed (adding the angular variable and checking the messy white space option).

It questions the non-scoped id_company variable and some unused variables.

'use strict';

angular.module("fluxo", ["ngRoute"]);

angular.module("fluxo").config(function ($routeProvider) {

    $routeProvider

    .when("/entradas", {
        templateUrl: "views/entradas.html",
        controller: "fluxoCtrl"
    })

    .when("/saidas", {
        templateUrl: "views/saidas.html",
        controller: "fluxoCtrl"
    })

    .otherwise({redirectTo: "/index"});

})

.factory('factCliente', ['$http', function($http) {
    return {
        getClientes: function(id_empresa) {
            return $http.post("php/index," id_empresa)
        }
    };
}])

.controller("fluxoCtrl", function ($scope, $http, factCliente) {
    $scope.clientes = [];

    var consultaClientes = function(data, status) {
        $scope.clientes = data;
    };

    factCliente.getClientes().success(consultaClientes);
});
  • I don’t understand, what is your suggestion? I made a modification that you said: Return { getData2: _getData2 }; Is that it? For the warning continues.

  • I tested on jslint it did not show any more errors.

  • Yeah, I think it’s really weird 'cause it seems to be all right!

  • You know another way to create an angular function that calls a function in a php class?

  • Yes, using ngResource since your php returns a JSON.

  • What would it be like? And how can I give you my php code to see?

  • You can. Post your code and we can analyze.

  • I posted my php.

  • I had forgotten to put, here, as I am called the class and the function of the class

Show 4 more comments

Browser other questions tagged

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