17

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....

8
  • Are you sure these lines of code are executed? Commented Apr 30, 2013 at 12:18
  • yes. console.debug after setting the comment logs the correct data. However $http.post doesn't seem to work. Commented Apr 30, 2013 at 12:20
  • posting to this url works, say from fiddler? and assuming idea with id 5 exists posting to this url works '/api/ideas/5/comments' ? Commented Apr 30, 2013 at 12:50
  • I checked in Charles Proxt and there doesn't seem to be a POST request happening... so I assume it's a problem with the frontend, not the backend? Commented Apr 30, 2013 at 13:39
  • 2
    Same error for me. $http.post fails silently, no error. Have tried about 10 different people's suggested syntax. Commented Dec 6, 2013 at 1:04

9 Answers 9

7

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";
Sign up to request clarification or add additional context in comments.

Comments

5

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);
                    });
            });

1 Comment

This makes sense. The linked page mentions that $http creates a promise, and promises are only resolved within the $digest cycle. @Dine, where does your code run? If it runs within a setTimeout or within a jQuery/DOM event listener function, then that's your problem. You need to call $scope.$apply(), which in turn triggers the $digest cycle.
2

I think, you just forgot some cruel ")" try

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

I did not test it yet, but I bet, this is the error regards

2 Comments

This is a very valid point, unfortunately this is not the problem as it is only a typo which slipped into stackoverflow but is actually correct in my app (I corrected it in stackoverflow now). Would most likely have caused am error in the console. So yeah - still not working...
Please Provide Us a Plunker .. where people can do something to Make it Working
1

If you are using angular 1.1.4+ check this thread https://github.com/angular/angular.js/issues/2431.

Basically if you are calling $http outside of Angular context you need to wrap $http callback in $scope.$apply. For more details look into https://github.com/angular/angular.js/issues/2794#issuecomment-18807158

Comments

1

I was struggling with the same problem. The way I solved it was to use .then() and registering the success and error callbacks as arguments. In your case:

$http.post('/api/items/'+$scope.item.id+'/comments', $scope.comment)
  .then(
    // success callback
    function(response) {
      console.debug("success - saved comment", $scope.comment);
    },
    // error callback
    function(response) {
      console.debug("error - saved comment", $scope.comment);
   }
);

Comments

0

You need to initialise the controller with the $http object. Same goes for the other Angular services you wish to use.

E.g.:

function myCtrl($scope, $http) {
  // controller code
}

1 Comment

I did inject the $http object. Thanks for the suggestion though.
0

You can try.

Angular js post call:

$http({
        url:'/api/ideas/'+$scope.item.id+'/comments', $scope.comment,
        method : 'POST'
    }).success(function(data, status, headers, config){
    }).error(function(data, status, headers, config){
    });

Rest Controller:

@RequestMapping
    (value = "/api/ideas/{item_id}/comments/{comment}", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    public void updateComments(@PathVariable String item_id,@PathVariable String comment) {
        }

Comments

0
//set arg
var arg = { name: $scope.name,
           tel: $scope.tel} 
// config 
var req = {
                method: 'POST',
                url: '/pServices/sellers/addNew',
                headers: {'Content-Type': 'application/json'},
                data: arg
            }
//POST data to server 
$http(req).then(function(data, status, headers, config){
                if(data['data']['status'])
                 console.log('success') ;

            }, function(data, status, headers, config){
                 console.log(data['data']['message']) 
            });

1 Comment

it would be better if you can add some explanation about your answer.
-1
angular.module('RestService', [

]).factory('$RestService', [
    '$http', 'ApiUrl',
    function ($http, ApiUrl) {
        return {          
            Functioname: function (request) {
                var Requesturl = ApiUrl + "/Functionname";//www.test.com/getuserdata
                return this.Post(Requesturl, request);//request :parameter which you want to pass in post request
            },
            Post: function (ResultUrl, RequestParameterData) {
                var PostResponse = $http({
                    url: ResultUrl,
                    method: "POST",
                    dataType: "",
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
                    data: RequestParameterData
                });
                return PostResponse;
            },
            Get: function (ResultUrl, RequestParameterData) {
                var PostResponse = $http({
                    url: ResultUrl,
                    method: "GET",
                    dataType: "",
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
                    data: RequestParameterData
                });
                return PostResponse;
            }

        };
    }


]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.