aWebDeveloper
aWebDeveloper

Reputation: 38352

Post form data with $resource

Following code post form data as json and not key value pair.

service

            $resource(apiPath, {
                Id: '@Id',
                apt_id: user_info.apt_id,
                mauth_token: user_info.mauth_token,
                mauth_account_id: user_info.mauth_acnt_id,
                rest: 1,
            }, {
                save:{
                    method:'POST',
                    headers : {'Content-Type': 'application/x-www-form-urlencoded'}
                }
            });

controller

.controller('BroadcastSmsSendCtrl', function($scope, $ionicLoading, $ionicActionSheet, $state, $timeout, $location, BroadcastSmsSvcs, GetUserCountHttpSvcs) {
            $scope.entry = new BroadcastSmsSvcs();

            $scope.doSubmit = function() {
                BroadcastSmsSvcs.save({}, $scope.entry);
            };
        });

Form data

Upvotes: 1

Views: 5841

Answers (3)

CodeArtist
CodeArtist

Reputation: 5684

AngularJs provides a service which transforms to jQuery like serialization object.

Instead of json serialization: {"id": 1, "name": "whatever"}

It becomes: id=1&name=whatever

So simply you can do:

save:{
    method: "POST",
    headers : {"Content-Type": "application/x-www-form-urlencoded"}, 
    transformRequest: function(data) {
        return $httpParamSerializerJQLike(data);
    }
}

Note: In your service you have to inject the $httpParamSerializerJQLike service

Upvotes: 12

aWebDeveloper
aWebDeveloper

Reputation: 38352

Add the following in your .config() function

 $httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
 $httpProvider.defaults.transformRequest.unshift(function (data, headersGetter) {
     var key, result = [], response;
     if(typeof data == "string") { //$http support
            response = data;
     } else {
            for (key in data) {
                if (data.hasOwnProperty(key)) {
                    result.push(encodeURIComponent(key) + "=" + encodeURIComponent(data[key]));
                }
            }
            response = result.join("&");
        }
        return response;
});

Upvotes: 3

WillyGuevara
WillyGuevara

Reputation: 31

try adding this to your $resource object

headers : {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest : function(obj){
      var str = [];
      for(var p in obj)
        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
      return str.join("&");
    }
  }

Upvotes: 3

Related Questions