AngularJS – How to POST Data using AJAX & Spring MVC – Part 1

The article presents the code example that one may use to post data to server using AngularJS $http service, while working with Spring MVC web application. The same is demonstrated in the following page: http://hello-angularjs.appspot.com/angularjs-http-service-ajax-post-code-example. This article is first in the series of articles on different techniques that could be used to POST different formats of data to the server when working with AngularJS and Spring MVC. In this article, the code samples demonstrate how to post plain HTML text data (text/html) format to the server.

Following are key steps:

  • Create Spring MVC web controllers methods
  • Create AngularJS controller method using $http service to post data
  • Create view to receive input data

Spring MVC Controller Methods

Following are different controller methods that will be required for first, accessing the page and then, posting the data using AJAX.

The code below is used to access the main web page from where AJAX request will be posted.
@RequestMapping(value = "/angularjs-http-service-ajax-post-code-example", method = RequestMethod.GET)
public ModelAndView httpServicePostExample( ModelMap model ) {
	return new ModelAndView("httpservice_post");
}
The code below is used to receive request parameters in html-text format (text/html) when posted using AJAX.
@RequestMapping(value = "/savecompany", method = RequestMethod.POST)
public  @ResponseBody String saveCompany( @RequestParam("name") String name,
		@RequestParam("employees") long employees,
		@RequestParam("headoffice") String headoffice) {		
	//
	// Code processing the input parameters
	//		
	return "The company data (name: " + name + ", employees: "+ String.valueOf( employees ) + ", headoffice: " + headoffice + ") is saved";
}

AngularJS Controller Method using $http Service

Following are set of code that needs to be written to post the AJAX request data in plain text format (text/plain). Before going over the code, pay attention to following:

  • The data is posted in the format, n1=v1&n2=v2&n3=v3. Posting this data without the code explained in next step throws an error. This is because “Content-Type” for $http.post defaults to ‘application/json’, while we are trying to send the data in plain text, name-value, traditional format. Check this link for detail, https://docs.angularjs.org/api/ng/service/$http.
  • Define a global configuration and set the ‘Content-Type’ of POST method to something such as following that demonstrated in following code. Pay attention to the fact that you would be required to include angular-resource.js script for working with ngResource dependency.
    var helloApp = angular.module("helloApp", ['ngResource']);
    
    helloApp.config(['$httpProvider', function ($httpProvider) {    
    	$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
    }]);
  • Define the $http code to post the data to server in the way sich as that shown below.
    $scope.addRowAsync = function(){
    // Add the data to the model
    //
    $scope.companies.push({ 'name':$scope.name, 'employees': $scope.employees, 'headoffice':$scope.headoffice });
    // Writing it to the server
    //
    var data = 'name=' + $scope.name + '&employees=' + $scope.employees + '&headoffice=' + $scope.headoffice;
    $http.post('/savecompany', data )
    .success(function(data, status, headers, config) {
    $scope.message = data;
    })
    .error(function(data, status, headers, config) {
    alert( "failure message: " + JSON.stringify({data: data}));
    });
    // Making the fields empty
    //
    $scope.name='';
    $scope.employees='';
    $scope.headoffice='';
    };

View to Receive Input Data

Following code represents view from where data is entered and submitted. Pay attention to ng-submit directive.

<form class="form-horizontal" role="form" ng-submit="addRowAsync()">
     <div class="form-group">
        <label class="col-md-2 control-label">Name</label>
            <div class="col-md-4">
                 <input type="text" class="form-control" name="name"
                  ng-model="name" />
            </div>
    </div>
    <div class="form-group">
        <label class="col-md-2 control-label">Employees</label>
            <div class="col-md-4">
                <input type="text" class="form-control" name="employees"
                 ng-model="employees" />
            </div>
    </div>
     <div class="form-group">
          <label class="col-md-2 control-label">Headoffice</label>
             <div class="col-md-4">
                 <input type="text" class="form-control" name="headoffice"
                  ng-model="headoffice" />
             </div>
     </div>
     <div class="form-group">
           <div style="padding-left:110px">
              <input type="submit" value="Submit" class="btn btn-primary"/>
           </div>
     </div>
</form>



Ajitesh Kumar
Follow me
Latest posts by Ajitesh Kumar (see all)

Ajitesh Kumar

I have been recently working in the area of Data Science and Machine Learning / Deep Learning. In addition, I am also passionate about various different technologies including programming languages such as Java/JEE, Javascript, Python, R, Julia etc and technologies such as Blockchain, mobile computing, cloud-native technologies, application security, cloud computing platforms, big data etc. I would love to connect with you on Linkedin.
Posted in Java, Javascript. Tagged with , , , .

4 Responses

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload the CAPTCHA.