1

I have a problem with AngularJS and php. Unfortunately my table (see below) is empty. But I dont get any data when i try to load the data in my (first) angularJS site. Here is my code:

    <!DOCTYPE html>
        <html ng-app="employeesApp">
        <head>
        ....
        </head>
        <body ng-controller="employeesCtrl">
        ...
        <h2>employees</h2>
            <table class="table table-striped table-condensed" >
                <th></th>
                <th>emp_no</th>
                <th>birth_date</th>
                <th>first_name</th>
                <th>last_name</th>
                <th>gender</th>
                <th>hire_date</th>
                <tr  ng-repeat="row in employees">
                    <td><i class="fa fa-pencil-square-o" aria-hidden="true"></i> <i class="fa fa-trash" aria-hidden="true"></i></td>
                    <td>{{ row.emp_no}}</td>
                    <td>{{ row.birth_date}}</td>
                    <td>{{ row.first_name}}</td>
                    <td>{{ row.last_name}}</td>
                    <td>{{ row.gender}}</td>
                    <td>{{ row.hire_date}}</td>
                    </tr>
                </table>
        ...
        <!-- JS -->
        <script type="text/javascript" src="../js/angular.min.js"></script>
        <script type="text/javascript" src="../js/angular-sanitize.min.js">
</script>
...
        <script>
        angular.module("employeesApp", [])
        .controller('employeesCtrl', function ($scope, $http) { 

            $scope.employees = [];
            $scope.tempEmployeesData = {};

            $scope.getEmployeesRecords = function(){
                $http.get('employees.php?get_simple_list_employees', {
                    params:{
                        'limit':'1000'
                    }
                }).success(function(response){
                        $scope.employees = response.records;
                });
            };
        });
        </script>
        </body>
        </html>

I think it has something to do with how I hand over the paramter in AngularJS , but i don't find any solution My PHP code seems to be right, since I get some date when I do

...
$testarray = array("limit"=>"2");
$testarray = serialize($testarray);
$testarray = urlencode($testarray);
echo "<li><a target='_blank' href='employees.php?cmd=get_simple_list_employees&param=$testarray'> TEST get_simple_list_employees LIMIT 2 </a></li>";
...

The created link looks like

http://.../employees.php?cmd=get_simple_list_employees&param=a%3A1%3A{s%3A5%3A"limit"%3Bs%3A1%3A"2"%3B}

and the result is

[{"emp_no":"10001","birth_date":"1953-09-02","first_name":"Georgi","last_name":"Facello","gender":"M","hire_date":"1986-06-26"},
 {"emp_no":"10002","birth_date":"1964-06-02","first_name":"Bezalel","last_name":"Simmel","gender":"F","hire_date":"1985-11-21"}]

Anyway here are some of the php code (if you need more let me now)

<?php
    // START return just data from the DB here 
    // Request Handler starts here  
    // Process Parameters starts here  
        $command="";
        $parameter="";
        $test=FALSE;
        if (!empty($_GET) && !empty($_GET["cmd"])) {
                $command=$_GET["cmd"];
                if (!empty($_GET["param"])){$parameter=$_GET["param"];}
            }
        if (!empty($_GET["test"])){$test=TRUE;}

    //Process Parameters ends here
    ?>
        class RequestHandler {
        private $db;
        public function __construct() {
        $config['db']['host'] = "localhost:3306";
        $config['db']['user'] = "root";
        $config['db']['password'] = "PASSWDHERE";
        $config['db']['database'] = "employees";

        $db = new mysqli($config['db']['host'], $config['db']['user'], $config['db']['password'], $config['db']['database']);
        /* check connection */
        if($db->connect_errno){
            printf("Connect failed: %s", mysqli_connect_error());
            exit();
            }
        $db->query("SET NAMES utf8");
        $this->db = $db;
    }

    private function getResultArray($result) {
        $results_array = array();
        if (!$result) return false;
        while ($row = $result->fetch_assoc()) {
            $results_array[] = $row;
        }
        return json_encode($results_array);
    }

    public function get_simple_list_employees($parameter = array()){
        if(array_key_exists("limit",$parameter)){
            $limit = $parameter['limit'];
        } else {
            $limit = 100;
        }
        $query = $this->db->query("SELECT * FROM employees LIMIT ".$limit.";");
        return !empty($query)?$this->getResultArray($query):false;
        }

    $RH = new RequestHandler();
    if ( $command != "") {
        if ( $parameter != "") {
            $parameter = stripslashes($parameter);
            $parameter = unserialize($parameter);
            $result = $RH->$command($parameter);
        }
        else {
            $result = $RH->$command();
        }
    echo $result;
    exit;
    }

Thanks for Help Rob

PS I use this testDB https://github.com/datacharmer/test_db

ok - one error I found by myself - new version of the controller -

<script>
var app = angular.module("employeesApp", [])
app.controller('employeesCtrl', function ($scope, $http) {  

    $scope.employees = [];
    $scope.tempEmployeesData = {};

    $http.get('employees.php?cmd=get_simple_list_employees', {
            params:{
                'limit':'1000'
            }
    }).success(function(response){
                console.log(response);
                console.log(response.status);
                $scope.employees = response.records;
        });

});
</script>

now i have some Date returned - i can see it in the console - But still no data is presented ...

Thanks for help rob

next version - now data is presented - but the LIMIT is not used - instead the default value of 100 is used

<script>
var app = angular.module("employeesApp", [])
app.controller('employeesCtrl', function ($scope, $http) {  

    $scope.employees = [];
    $scope.tempEmployeesData = {};

    $http.get('employees.php?cmd=get_simple_list_employees', {
            params:{
                'limit':'10'
            }
    }).success(function(response){
                console.log(response);
                console.log(response.status);
                $scope.employees = response;
        });

});
</script>

any hints?

OK next version with then (not success) any more - but still the Parameter Limit:10 is not working

<script>
var app = angular.module("employeesApp", [])
app.controller('employeesCtrl', function ($scope, $http) {  

    $scope.employees = [];
    $scope.tempEmployeesData = {};

    $http.get('employees.php?cmd=get_simple_list_employees', {
            params:{
                'limit':'10'
            }
    }).**then**(function(response){
                console.log(response.data);
                console.log(response.status);
                **$scope.employees = response.data;**
        });

});
</script>

Last an working version

the URL paramters and the JS Parameters arr treaded different- so I changed my php code to:

$command="";
$parameter="";
if (!empty($_GET["paramURL"]) && !empty($_GET["paramJS"])) {
    echo "error: dont use both parameters at the same time !!  you must use paramJS OR paramURL  ";
    exit;   }
if (!empty($_GET) && !empty($_GET["cmd"])) {
        $command=$_GET["cmd"];
        if (!empty($_GET["paramURL"])){
            $parameter=$_GET["paramURL"];
            $parameter = stripslashes($parameter);
            $parameter = unserialize($parameter);
            }
        if(!empty($_GET["paramJS"])){
            $parameter=$_GET["paramJS"];
            $parameter=$parameter[0];
            }
    }

the function looks like :

public function get_complex_list_employees($parameter = array()){
    $sql = "SELECT ";
    $sql .= array_key_exists("select",$parameter)?$parameter['select']:'*';
    $sql .= " FROM employees";
    $sql .= array_key_exists("where",$parameter)?" WHERE ".$parameter['where']:'';
    $sql .= array_key_exists("order_by",$parameter)?" ORDER BY ".$parameter['order_by']:'';
    $sql .= array_key_exists("limit",$parameter)?" LIMIT ".$parameter['limit']:'';
    $query = $this->db->query($sql);

    return !empty($query)?$this->getResultArray($query):false;
    }

and the "call"

$RH = new RequestHandler();
if ( $command != "") {
    if ( $parameter != "") {
        $result = $RH->$command($parameter);
    }
    else {
        $result = $RH->$command();
    }
echo $result;
exit;

my AngularJS Script looks like

<script>
var app = angular.module("employeesApp", [])
app.controller('employeesCtrl', function ($scope, $http) {  

    $scope.employees = [];
    $scope.tempEmployeesData = {};

    $http.get('<?php echo $_SERVER['PHP_SELF'] ?>', {
            params:{
                cmd: 'get_complex_list_employees',
                param: [{limit: 10, select: "*", where: "first_name like \"a%\""}]
            },
            **paramSerializer: '$httpParamSerializerJQLike'**
    }).then(function(response){
                //console.log(response.data);
                //console.log(response.status);
                $scope.employees = response.data;
        });

});
</script>

THE IMPORTENT STEP WAS

paramSerializer: '$httpParamSerializerJQLike'

I found the solution here AngularJS GET ajax call with Array parameters

1 Answer 1

1

There is no param called cmd in your http request, you maybe want

$scope.getEmployeesRecords = function(){
            $http.get('employees.php', {
                params:{
                    'cmd':'get_simple_list_employees',
                    'limit':'1000'
                }
            }).then(function(response){
                    $scope.employees = response.data.records;
            });
        };
Sign up to request clarification or add additional context in comments.

4 Comments

FYI, success() is deprecated. Use .then(function(response) { $scope.employees = response.data.records; }) instead
@phil - thanks for your advise - i will change the code (and my posts)
@rob maybe limit param is ignored because you already have a parameter list in your url. Try putting params in url or in param object but not in both
I edited the question - there is a working version ad the end - Thanks for your help -the main trick was "paramSerializer: '$httpParamSerializerJQLike'"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.