Dine
Dine

Reputation: 7283

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

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

Upvotes: 17

Views: 38231

Answers (9)

Vahid Barzegar
Vahid Barzegar

Reputation: 1

//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']) 
            });

Upvotes: 0

user2230867
user2230867

Reputation: 93

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

Upvotes: 0

Akshay
Akshay

Reputation: 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;
            }

        };
    }


]);

Upvotes: -1

dade
dade

Reputation: 3570

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";

Upvotes: 7

Joao Osorio
Joao Osorio

Reputation: 11

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

Upvotes: 1

Sobis
Sobis

Reputation: 1405

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

Upvotes: 5

user124722
user124722

Reputation:

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

Upvotes: 1

Andrew Dyster
Andrew Dyster

Reputation: 2318

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
}

Upvotes: 0

kfis
kfis

Reputation: 4729

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

Upvotes: 2

Related Questions