Posting a Form using AngularJS

The post() method of $http AngularJS service uses JSON form submission. That means, a JSON document is sent as the request body. You will need a REST web service to process the request. Most traditional web based handlers like Servlet or Struts action won’t be able to process it. In this article we will explore the issue and suggest a simple solution.

Let’s say that you do a form post like this:

$"/auth/login", {email: "", password:"letmein"});

This will issue a POST request like this (only relevant headers shown):

POST /auth/login HTTP/1.1
Content-Type: application/json;charset=UTF-8


A Servlet or Struts action will fail to parse the request as a regular form post. If you can not build a REST web service for whatever reason, then you have to do two things:

  1. Set the content type to “application/x-www-form-urlencoded”
  2. Set the request body to the name=value&name=value format.

The first problem is solved by doing this:

$["Content-Type"] = "application/x-www-form-urlencoded";

About the second, let’s create a utility class that formats user input in name value pairs.

function FormHelper() { = "";
 this.append = function(name, val) {
   if ( > 0) { += "&";
   } += encodeURIComponent(name); += "="; += encodeURIComponent(val);

We can now use the class like this:

$["Content-Type"] = "application/x-www-form-urlencoded";

var fh = new FormHelper();
fh.append("email", "");
fh.append("password", "letmein");

Now, the request will look like this (only relevant headers shown):

POST /auth/login HTTP/1.1
Content-Length: 40
Content-Type: application/x-www-form-urlencoded

2 thoughts on “Posting a Form using AngularJS

    • Good to know. In Java too you can map a posted JSON document to a Java object. But, that will require the use of a RESTful web service (using JAX-RS). What I meant is that a regular web application handler (like a Servlet in Java) does not process JSON POST requests.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s