How can I post data as form data instead of a request payload? How can I post data as form data instead of a request payload? ajax ajax

How can I post data as form data instead of a request payload?


The following line needs to be added to the $http object that is passed:

headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}

And the data passed should be converted to a URL-encoded string:

> $.param({fkey: "key"})'fkey=key'

So you have something like:

$http({    method: 'POST',    url: url,    data: $.param({fkey: "key"}),    headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}})

From: https://groups.google.com/forum/#!msg/angular/5nAedJ1LyO0/4Vj_72EZcDsJ

UPDATE

To use new services added with AngularJS V1.4, see


If you do not want to use jQuery in the solution you could try this. Solution nabbed from here https://stackoverflow.com/a/1714899/1784301

$http({    method: 'POST',    url: url,    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("&");    },    data: xsrf}).success(function () {});


I took a few of the other answers and made something a bit cleaner, put this .config() call on the end of your angular.module in your app.js:

.config(['$httpProvider', function ($httpProvider) {  // Intercept POST requests, convert to standard form encoding  $httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";  $httpProvider.defaults.transformRequest.unshift(function (data, headersGetter) {    var key, result = [];    if (typeof data === "string")      return data;    for (key in data) {      if (data.hasOwnProperty(key))        result.push(encodeURIComponent(key) + "=" + encodeURIComponent(data[key]));    }    return result.join("&");  });}]);