In the code below, the AngularJS $http
method calls the URL, and submits the xsrf object as a "Request Payload" (as described in the Chrome debugger network tab). The jQuery $.ajax
method does the same call, but submits xsrf as "Form Data".
How can I make AngularJS submit xsrf as form data instead of a request payload?
var url = 'http://somewhere.com/';
var xsrf = {fkey: 'xsrf key'};
$http({
method: 'POST',
url: url,
data: xsrf
}).success(function () {});
$.ajax({
type: 'POST',
url: url,
data: xsrf,
dataType: 'json',
success: function() {}
});
You can define the behavior globally:
So you don't have to redefine it every time:
For Symfony2 users:
If you don't want to change anything in your javascript for this to work you can do these modifications in you symfony app:
Create a class that extends Symfony\Component\HttpFoundation\Request class:
Now use you class in app_dev.php (or any index file that you use)
This is what I am doing for my need, Where I need to send the login data to API as form data and the Javascript Object(userData) is getting converted automatically to URL encoded data
This how my Userdata is
In your app config -
With your resource request -
As of AngularJS v1.4.0, there is a built-in
$httpParamSerializer
service that converts any object to a part of a HTTP request according to the rules that are listed on the docs page.It can be used like this:
Remember that for a correct form post, the
Content-Type
header must be changed. To do this globally for all POST requests, this code (taken from Albireo's half-answer) can be used:To do this only for the current post, the
headers
property of the request-object needs to be modified:The continued confusion surrounding this issue inspired me to write a blog post about it. The solution I propose in this post is better than your current top rated solution because it does not restrict you to parametrizing your data object for $http service calls; i.e. with my solution you can simply continue to pass actual data objects to $http.post(), etc. and still achieve the desired result.
Also, the top rated answer relies on the inclusion of full jQuery in the page for the $.param() function, whereas my solution is jQuery agnostic, pure AngularJS ready.
http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/
Hope this helps.