Badhon Jain
Badhon Jain

Reputation: 1007

Why Success or Error callback function not executing properly for $http.post in angularjs

I'm trying to communicate with server using following code.

$scope.Save = function () {
        $scope.loading = true;

        if ($scope.roleSetupModel.RoleID === "") {
            // Save
            //$scope.loading = true;
            $http.post('/SecurityModule/RoleSetup/AddRole', JSON.stringify($scope.roleSetupModel))
                .success(function (response) {
                    $scope.loading = false;
                    $('#addModal').modal('hide');
                    $scope.BindDataToGrid();
                    alert("Success");
                    toastr.success(response.Message);

                })
                .error(function (response) {
                    $scope.loading = false;
                    alert("Fail");
                    toastr.error(response.Message);

                });

        }
        else {
            $http.post('/SecurityModule/RoleSetup/EditRole',
                    JSON.stringify(convArrToObj($scope.roleSetupModel)))
                .success(function (response) {
                    $('#addModal').modal('hide');
                    $scope.loading = false;
                    toastr.success(response.Message);
                    $scope.BindDataToGrid();
                })
                .error(function (data) {
                    $scope.loading = false;
                    toastr.error(response.Message);
                });

        }
    }

But I'm getting wired behavior. The link is being hit everytime, I put a debugger there, but even before completing the request my page getting kind of refreshed making my model empty with out entering the success or error call back. I know a little about the promise object but couldn't make sense. What I'm doing wrong here?

Upvotes: 1

Views: 549

Answers (1)

charlietfl
charlietfl

Reputation: 171690

My guess is you aren't binding $scope.Save() to ng-submit of <form> and have it being triggered by a submit button, or you have not followed the docs for forms

If form is set up with:

<form name="formScopeName" ng-submit="Save()" novalidate>

Your $http should work fine. However if you have action set on form angular interprets that as you want to submit without ajax nd use default browser process. So make sure action attribute doesn't exist.

Also note there is no reason to stringify the data yourself. This will be done automatically by $http internally. This could be causing error perhaps

You can also pass in $event for extra protection and then preventDefault. Generally this isn;t necessary however.

ng-submit="Save($event)"

JS

$scope.Save = function (event){
    event.preventDefult();
     .....

Upvotes: 2

Related Questions