How to post application/x-www-form-encoded?

19,792 views
Skip to first unread message

Eric Jain

unread,
Feb 14, 2012, 2:54:46 PM2/14/12
to AngularJS
How do I post data as application/x-www-form-encoded rather than json?

$http.post('/test', { foo : 1, bar : 2 });

Witold Szczerba

unread,
Feb 14, 2012, 4:46:30 PM2/14/12
to ang...@googlegroups.com
I am doing it like this:
/**
* On 'event:loginRequest' send credentials to the server.
*/
scope.$on('event:loginRequest', function(event, username, password) {
var payload = 'j_username=' + username + '&j_password=' + password;
var config = {
headers: {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}
}
$http.post('j_spring_security_check', payload,
config).success(function(data) {
if (data === 'AUTHENTICATION_SUCCESS') {
scope.$broadcast('event:loginConfirmed');
}
});
});

As you can see, the only problem is that I had to construct the
payload manually:
var payload = 'j_username=' + username + '&j_password=' + password;
instead of:
var payload = { j_username: username, j_password: password};
, which might be problematic when special characters are used.

If there is a better way, let me know someone :)

Regards,
Witold Szczerba

On 14 February 2012 20:54, Eric Jain <eric...@gmail.com> wrote:
> How do I post data as application/x-www-form-encoded rather than json?
>
> $http.post('/test', { foo : 1, bar : 2 });
>

> --
> You received this message because you are subscribed to the Google Groups "AngularJS" group.
> To post to this group, send email to ang...@googlegroups.com.
> To unsubscribe from this group, send email to angular+u...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/angular?hl=en.
>

Eric Jain

unread,
Feb 14, 2012, 6:35:22 PM2/14/12
to AngularJS
On Feb 14, 1:46 pm, Witold Szczerba <pljosh.m...@gmail.com> wrote:
> If there is a better way, let me know someone :)

Thanks, this works. I also discovered a JQuery function to build the
payload:

$.param({ foo : 1, bar : 2 }) -> "foo=1&bar=2"

Chris Odney

unread,
Feb 14, 2012, 6:36:09 PM2/14/12
to AngularJS
@Witold, instead of constructing the payload manually you could use
$.param({user:userName, pswd: password}). i.e. if you already have the
credentials object.

Chris.
Reply all
Reply to author
Forward
0 new messages