JustAce
JustAce

Reputation: 244

Passing value of variable from php to angular javascript

In my user controller, the lodgin function check if there's a data in inside my database and perform a condition whether it's true or false, My question is how can I pass the value of of $valid variable in my php and pass to it in my userlogin javascript? Sorry for my bad english.

PHP:

public function loginAction() {
  if (!isset($_POST['data']))
    jsonOut($response - > status = 'failed');

  $user_data = json_decode($_POST['data']);
  $response = new stdClass();

  $this - > users_model_instance - > student_username = $user_data - > username;
  $this - > users_model_instance - > student_password = $user_data - > password;

  $valid = $this - > users_model_instance - > Login();

  if ($valid) {

    jsonOut($response - > status = 'success');
  } else {

    jsonOut($response - > status = 'failed');
  }
}

JavaScript:

(function() {
  var app = angular.module("userlogin", []);

  app.controller("UserLoginController", ["$location", "ngDialog", "$scope", "httpRequest",
    function($location, ngDialog, $scope, httpRequest) {

      $scope.students = {};
      $scope.newStudents = {};
      $scope.startTest = false;
      $scope.students;

      $scope.submitLogin = function() {
        var request = {};
        request.url = '/account/users/login';
        request.method = 'POST';
        request.data = angular.toJson($scope.students);

        var onSuccess = function(data, status, headers, config, statusText) {

          if (status == 'true') {
            alert('success!');
            $location.url('/examdirection/');
          } else if (status == 'failed') {
            alert('failed!');
          }
        };
        httpRequest(request, $scope.response, onSuccess);
      };
    }
  ]);
})();

Upvotes: 0

Views: 535

Answers (1)

Okazari
Okazari

Reputation: 4597

Consider looking at $http to make your async requests. Here is an exemple :

Angular :

$scope.submitLogin = function() {
    //You don't need to serialize the data into json
    $http.post('/account/user/login', $scope.students).success(function(data){
        //We enter here when the http response status code is a success 2XX
        alert('success!');
        $location.url('/examdirection/');
    }).error(function(){
        //We enter here when the http response status code is an error 4XX, 5XX
        alert('failed!');
    });
};

Php (you'll need to find the way in your framework to set the response code of your $response):

if($valid){
    //It should look like $response->setStatusCode(200)
    //http_response_code is for pure php http manipulation
    http_response_code(200);
}else{
    //Choose the best http code in your case
    http_response_code(400);
}

Hope it'll help you out.

Upvotes: 1

Related Questions