Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular.js $http.post not working - no error

Tags:

angularjs

I'm trying to submit a new comment using $http. You might have guessed it from the title: it's not working. I tried the shore version and the long version, both fail. No console error.

This is my code:

$scope.comment = {};
$scope.comment["comment"] = message; // message defined somewhere else

$http.post('/api/items/'+$scope.item.id+'/comments', $scope.comment)
    .success(function(data, status, headers, config) {
         // this isn't happening:
         console.debug("saved comment", $scope.comment);
    })
    .error(function(data, status, headers, config) {
         // this isn't happening:
         console.debug("saved comment", $scope.comment);
    })
}

Anyone got any idea on how to make this work? Thanks!

UPDATE:

I'm doing it as a Jquery ajax call now, which is working fine. It'd be nice to get it to work with angular though. This is my JQuery code however:

            var request = $.ajax({
                url: '/api/items/'+$scope.item.id+'/comments',
                type: "POST",
                data: JSON.stringify($scope.comment),
                contentType: 'application/json; charset=utf-8',
                dataType: "json"
            });

            request.done(function(msg) {
                console.debug("saved comment", $scope.comment);
            });

            request.fail(function(jqXHR, textStatus) {
                alert( "Request failed: " + textStatus );
            });

If anyone has any ideas how to angularify this please tell me, would be nice to do it the proper way....

like image 340
Dine Avatar asked Apr 30 '13 11:04

Dine


2 Answers

Have you tried specifically setting the Content-Type before making the request?

I had the same issue and setting Content-Type fixes it.

$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
like image 160
dade Avatar answered Oct 02 '22 14:10

dade


Maybe this will help you. I had similiar problem with get call : AngularJS $http not firing get call

I solved it with solution, found here https://github.com/angular/angular.js/issues/2794#issuecomment-18807158, so I wraped my call function with $scope.$apply.

$scope.$apply(function() {
                console.log('Klic na ID ' + data.context.id);
                $scope.commonController.getData('orgunit/' + data.context.id + '?jsonDepth=3')
                    .success(function(workpositionData,status,headers,config) {
                        console.log('Klic na ID ' + data.context.id + ' OK');
                        $scope.workPositions = workpositionData.workPositions;
                    }).error(function(data,status,headers,config) {
                        commonController.error('Pri branju delovnih mest je prišlo do napake: '+data.description);
                    });
            });
like image 32
Sobis Avatar answered Oct 02 '22 15:10

Sobis