Search code examples
javascriptangularjsangular-resource

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


Solution

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