0

I try to make an authentication using angualrJS and php. I tested it by console.log, when the password is incorrect I get error message, and when the password is correct I don't get anything, in this case, I want to be riderected to other view, how can I do please:

app.js

app.controller('loginCtrl', function($scope, $location,$state,$http,$window){

    $scope.submit = function()
    {
        data = {
            'NomClient' : $scope.NomClient,
            'mdp' : $scope.mdp
        };

        $http.post('http://localhost/deb/login.php', data)
        .success(function(data, status, headers, config)
        {
          // $window.location.href = '#/admin';
            console.log(data);
        })
        .error(function(data, status, headers, config)
        {
            console.log('error');
        });
    }

});

login.php

 <?php  

$data = json_decode(file_get_contents("php://input"));

 $connect = mysqli_connect("localhost", "root", "", "test");  


 if(count($data) > 0)  
 { 
$NomClient=mysqli_real_escape_string($connect, $data->NomClient);
$mdp=mysqli_real_escape_string($connect, $data->mdp);


$query = 'SELECT * FROM `client` WHERE NomClient = "'.$NomClient.'" AND   mdp= "'.$mdp.'"';

$q = mysqli_query($connect , $query);

if(mysqli_num_rows($q) > 0 )
        { 
            $_SESSION["logged_in"] = true; 
            $_SESSION["naam"] = $NomClient; 
        }
        else
        {
            echo 'The username or password are incorrect!';
        }

}
 ?>

As you see, I have a comment line in app.js: // $window.location.href = '#/admin'; I put it as comment because when I put it, it redirects me to admin view however the password is incorrect.

Thanks in advance

Touria
  • 87
  • 7

6 Answers6

0

With AngularJS you can use the $location service

$Location - Documentation

Try using:

$location.path("your new path here")

For an example: please refer to the following answer to another post:

https://stackoverflow.com/a/14387747/7018180

0

.success is a property of $http service so if there would be some value in data variable the $window.location is eventually going to get called.. so to improve that you can use if condition inside $http service which would check the passed username and password with the response that it would get from the service and then in if condition you can redirect it to another page.

app.service('AuthenticationService', function ($http, $window){
    this.login = function (username, password) {
        return $http({
            url: 'http://localhost/deb/login.php',
            method: 'POST',
            params: {
                NomClient : username,
                mdp : password
            }
        })
    };
});

app.controller('loginCtrl', function ($scope, $state, $http, $window, AuthenticationService, $remember) {
    $scope.submit = function()
    {
        AuthenticationService.login($scope.NomClient,$scope.mdp)
        .then(function(response) {
            if (response.data.NomClient == $scope.NomClient && response.data.mdp == $scope.mdp) 
            {
                $state.go('application.home');
            }
            else {
                alert('Credentials do not match our records. Please try again.');
            }
        })
    }
});

and instead of $window.location you can use $state.go functionality of angularJS. It would redirect your page to the specific state that would be mentioned and it would look for that state in route file and would execute that state along with its templateUrl and controller.

Abhishek Solanki
  • 43
  • 1
  • 1
  • 8
  • it doens't redirect to other view in the two cases (when password and user are correct and when they are not correct), And I don't get any error message – Touria May 30 '17 at 10:16
  • i have updated my answer's code part here's the link https://stackoverflow.com/a/44259143/6859483 please have a look at it try creating service and then calling that service and passing the data simultaneously this code works perfectly fine for me it should for you i guess. – Abhishek Solanki May 30 '17 at 10:40
  • Thank you but unfortunatly It doen't work , I always get alert message however the password and username are correct!! – Touria May 30 '17 at 10:57
0

Try this code in login.php

if(mysqli_num_rows($q) > 0 )
  { 
       $_SESSION["logged_in"] = true; 
       $_SESSION["naam"] = $NomClient; 
       $result['code'] = 200;
       $result['message'] ='Logged In';
  }
  else
  {

       $result['code'] = 603;
       $result['message'] ='The username or password are incorrect!';
  }

$resultstring = json_encode($result);
$resultstring = str_replace("null",'""',$resultstring);
echo $resultstring ;
die;

And check result code in js if it is 200 then it will be in succes other wise in error.

Arshad Shaikh
  • 564
  • 1
  • 3
  • 13
  • Yes when the password is right I get sucess and when it s wrong I get error message, but in the two cases, I m redirected to the other view, not only wheb its coirrect – Touria May 30 '17 at 10:11
  • No, you have to redirect the login page if it is wrong password and redirect to home page when password is correct. In angular some time we have to refresh the page and its best if we refresh the page after successful login – Arshad Shaikh May 30 '17 at 10:36
0

Change .success\.error to .then(), Change your code like :

   $http.post('http://localhost/deb/login.php', data).then(function(response) {          
            console.log(response.data);
            $window.location.href = '#/admin';
          }, function(error) {
            console.log('error');
     });
anoop
  • 3,812
  • 2
  • 16
  • 28
  • Yes when the password is right I get sucess and when it s wrong I get error message, but in the two cases, I m redirected to the other view, not only wheb its coirrect – Touria May 30 '17 at 10:13
  • @SalamSalam: as per your code, it shouldn't be.. there might be routing happening at some other event (check for `subscribe\.on`).. or could you create plunker\fiddle to reproduce?., also post your `html` code where you calling `submit`. – anoop May 30 '17 at 10:16
  • @SalamSalam: as per updated html, it still makes no difference IMO answer should still valid, please create plunker\fiddle to reproduce your issue. – anoop May 30 '17 at 14:08
  • I tried to create it , but I don"t know how manage database in it, how can I do please! – Touria May 30 '17 at 14:10
  • @SalamSalam: see this example $http.post with `.then` [fiddle](http://jsfiddle.net/0L3mygog/) – anoop May 30 '17 at 14:20
0

Here's properly working code for your question tested properly. if you are still looking for a solution

app.js

app.controller('loginCtrl', function ($scope, $http,$state) {
    $scope.submit = function ()
    {
        $scope.data = {
            username: $scope.username,
            password: $scope.password
        }

        $http.post('http://localhost/HTML5Application/public_html/login.php', {serviceData: $scope.data})
                .success(function (data) {
                    alert(data);
                    $state.go('newState');
                })
                .error(function (data) {
                    alert("problem with service call");
                });
    };
});


login.php

    $data = json_decode(file_get_contents("php://input"));

    $connect = mysqli_connect("localhost", "root", "", "embroidery");

    if (count($data) > 0) {
        $username = mysqli_real_escape_string($connect, $data->serviceData->username);
        $password = mysqli_real_escape_string($connect, $data->serviceData->password);
        $query = 'SELECT * FROM `client` WHERE username = "' . $username . '" AND   password= "' . $password . '"';

        $q = mysqli_query($connect, $query);

        if (mysqli_num_rows($q) > 0) {
            $_SESSION["logged_in"] = true;
            $_SESSION["name"] = $username;
            echo $_SESSION["name"];
        } else {
            echo 'The username or password are incorrect!';
        }
    }
    ?>


login.html

<div class="list list-inset" ng-controller="loginCtrl">
    <label class="item item-input">
        <input type="text" placeholder="Username" required="" ng-model="username"> 
    </label> 
    <label class="item item-input">
        <input type="password" placeholder="Password" ng-model="password"> 
    </label> 
    <button class="button button-block button-positive" name="submit" ng-click="submit()">Login</button>       
</div>
Abhishek Solanki
  • 43
  • 1
  • 1
  • 8
  • I still searching for the solution, but when I tried to implement yours, I get this error: "undefinded property '$serviceData', and after that it redirect me to admin view in the two cases (however the password is wrong) – Touria May 31 '17 at 10:36
  • can i see your updated code because i haven't used $serviceData anywhere in the application. – Abhishek Solanki May 31 '17 at 11:05
  • I mean ServiceDate that you in php file and js file, I get error message that s undefinded – Touria May 31 '17 at 11:09
  • have you updated path to your local machine's path in $http.post method ?? – Abhishek Solanki May 31 '17 at 11:43
0

Thank you all, this is the solution of this question, solved by "Mr_Perfect": we have just to add a condittion in suceess:

$http.post('http://localhost/deb/login.php', data)
        .success(function(data, status, headers, config,result)
        {

            console.log(data);
            if(data.code == 200){
            $state.go('admin');
          }
        })
        .error(function(data, status, headers, config, rsult)
        {

            console.log('error');

        });

Thanks to you all

Touria
  • 87
  • 7