phpangularjscodeigniterserver-side-validation

AngularJS post json data + server side validation in codeigniter


I've searched all over the internet that how to form validate data sent by Angular js $http POST request in codeigniter.

For clear understanding I've posted completed HTML data. I believe that most of the developer are looking for this solution.

Here is my HTML Form:

<!DOCTYPE html>
<html>
    <head>
        <style>
            input[type="text"].ng-invalid{border: 1px solid red; }
        </style>
    </head>
    <body ng-app="app" ng-controller="ctrl">

        <form name="test_form" ng-submit="send_data()">
            <input type="text" name="email" ng-model="email">
            <span ng-show="test_form.email.$invalid - required">Required</span>

            <input type="password" name="password" ng-model="password">
            <span ng-show="test_form.email.$invalid - required">Required</span>

            <button type="submit">Submit</button>
        </form>


        <script src="<?php echo base_url('assets/angular/angular.min.js'); ?>" type="text/javascript">
        </script>
        <script>
                    angular.module('app', [])
                    .controller('ctrl', function ($scope, $http) {
                        $scope.send_data = function () {
                            $http({
                                method: "POST",
                                url: "<?php echo base_url('login/test_angular_validate'); ?>",
                                data: {email: $scope.email, password: $scope.password},
                                headers : {'Content-Type': 'application/x-www-form-urlencoded'}
                            }).then(function (success) {
                                console.log(success);
                            }, function (error) {

                            })
                        }
                    });
        </script>
    </body>
</html>

Backend Codeigniter Login Controller Function

<?php
public function test_angular_validate() {
    $form_data = json_decode(file_get_contents("php://input"), true);

    $this->load->helper(array('form', 'url'));

    $this->load->library('form_validation');

    $this->form_validation->set_rules('email', 'email', 'required|min_length[3]');
    $this->form_validation->set_rules('password', 'password', 'required');

    if ($this->form_validation->run() == FALSE) {
        echo 'failed';
        print_r(validation_errors());
    } else {
        echo 'success';
    }
}
?>

When is send html form data using angular $http POST request I'm unable to validate that data using codeigniter form validation library. It throws an validation error as given in this image.


Solution

  • Codeigniter access the super global $_POST for its validation. Your JSON data is not binded to this superglobal. So you need to set it up manually:

    $_POST = json_decode(file_get_contents("php://input"), true);
    

    You can also POST your data URLENCODED. In that way you your POST params will be available in $_POST without a manually set.

    $http({
        method: 'POST',
        url: "<?php echo base_url('login/test_angular_validate'); ?>",
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        data: {
            email: $scope.email, 
            password: $scope.password
        },
        transformRequest: function(obj) {
            var str = [];
            for(var p in obj)
                str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
            return str.join("&");
        },
    }).then(function (success) {
        console.log(success);
    }, function (error) {
    
    });