harry-potter
harry-potter

Reputation: 2049

HTTP request with angularJS

I'm trying to make an HTTP request from AngularJS v1.5.8 but it does not work.

I have a simple HTML form and a submit button that calls my login() function:

<body ng-app="myApp" ng-controller="loginController">
......
......
......

<div
class="col-md-4 col-md-offset-4 col-sm-4 col-sm-offset-3 col-xs-6 col-xs-offset-3">
<button type="submit" class="btn btn-default" ng-submit="login()">Submit</button>
</div>

And this is my loginController

var app = angular.module ("myApp", []);
app.controller("loginController", function($scope, $http){

    $scope.username = "";
    $scope.password = "";

    $scope.login = function() {

        $http(
                {
                    method : 'POST',
                    url : SessionService.getserverName()+'/RestServices/services/login/add',
                    headers : {
                        'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
                    },
                    data : {
                        username : $scope.username,
                        password : $scope.password
                    }
                    }).success(function(response, status) {
                    if (response.result.success && status == 200) {
                    $log.info('OK');

                    $location.path('/newPage.html');
            } 
        })
    }
});

The HTTP request does not really run.

Upvotes: 1

Views: 120

Answers (3)

Rizwan Jamal
Rizwan Jamal

Reputation: 1284

Try with using the structure below ..

$http({
    url: 'put url here',
    method: "put action here just like GET/POST",
    data: { 'name': 'Rizwan Jamal' }
})
.then(function (resp) {
    //TODO: put success logic here
},
function (resp) {
    //TODO:  put failed logic here
}

);

.then() method fires in both the success and failure cases. The then() method takes two arguments a success and an error callback which will be called with a response object.

NOTE : If you are not using form validation so please change ng-submit with ng-click.. I hope this solution will work for You :)

Upvotes: 1

Jaydeep Gondaliya
Jaydeep Gondaliya

Reputation: 331

app.js

'use strict';
// Declare app level module which depends on filters, and services
var app= angular.module('myApp', ['ngRoute','angularUtils.directives.dirPagination','ngLoadingSpinner']);
app.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/login', {templateUrl: 'partials/login.html', controller: 'loginCtrl'});
  $routeProvider.when('/home', {templateUrl: 'partials/home.html', controller: 'homeCtrl'});
  $routeProvider.when('/salesnew', {templateUrl: 'partials/salesnew.html', controller: 'salesnewCtrl'});
  $routeProvider.when('/salesview', {templateUrl: 'partials/salesview.html', controller: 'salesviewCtrl'});
  $routeProvider.when('/users', {templateUrl: 'partials/users.html', controller: 'usersCtrl'});
    $routeProvider.when('/forgot', {templateUrl: 'partials/forgot.html', controller: 'forgotCtrl'});


  $routeProvider.otherwise({redirectTo: '/login'});


}]);


app.run(function($rootScope, $location, loginService){
    var routespermission=['/home'];  //route that require login
    var salesnew=['/salesnew'];
    var salesview=['/salesview'];
    var users=['/users'];
    $rootScope.$on('$routeChangeStart', function(){
        if( routespermission.indexOf($location.path()) !=-1
        || salesview.indexOf($location.path()) !=-1
        || salesnew.indexOf($location.path()) !=-1
        || users.indexOf($location.path()) !=-1)
        {
            var connected=loginService.islogged();
            connected.then(function(msg){
                if(!msg.data)
                {
                    $location.path('/login');
                }

            });
        }
    });
});

loginServices.js

'use strict';
app.factory('loginService',function($http, $location, sessionService){
    return{
        login:function(data,scope){
            var $promise=$http.post('data/user.php',data); //send data to user.php
            $promise.then(function(msg){
                var uid=msg.data;
                if(uid){
                    scope.msgtxt='Correct information';
                    sessionService.set('uid',uid);
                    $location.path('/home');
                }          
                else  {
                    scope.msgtxt='incorrect information';
                    $location.path('/login');
                }                  
            });
        },
        logout:function(){
            sessionService.destroy('uid');
            $location.path('/login');
        },
        islogged:function(){
            var $checkSessionServer=$http.post('data/check_session.php');
            return $checkSessionServer;
            /*
            if(sessionService.get('user')) return true;
            else return false;
            */
        }
    }

});

sessionServices.js

'use strict';

app.factory('sessionService', ['$http', function($http){
    return{
        set:function(key,value){
            return sessionStorage.setItem(key,value);
        },
        get:function(key){
            return sessionStorage.getItem(key);
        },
        destroy:function(key){
            $http.post('data/destroy_session.php');
            return sessionStorage.removeItem(key);
        }
    };
}])

loginCtrl.js

'use strict';

app.controller('loginCtrl', ['$scope','loginService', function ($scope,loginService) {
    $scope.msgtxt='';
    $scope.login=function(data){
        loginService.login(data,$scope); //call login service
    };

}]);

Upvotes: -2

Silvinus
Silvinus

Reputation: 1445

ngSubmit attribute work only on form element. see https://docs.angularjs.org/api/ng/directive/ngSubmit.

Try to move

ng-submit="login()"

to your form element

Upvotes: 3

Related Questions