Categories: JavaJavascript

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

I have been recently working in the area of Data analytics including Data Science and Machine Learning / Deep Learning. I am also passionate about 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. Check out my latest book titled as First Principles Thinking: Building winning products using first principles thinking.

View Comments

  • Thanks a lot, I have been looking for this several hours! you saved me!

  • I suppose the SpringController method which you are calling returns a string, which obviously specifies your home page, as a part of refresh.

    This will supress the file from getting downloaded due to the "org.springframework.web.servlet.view.InternalResourceViewResolver" which you would have specified in your applicationContext.

    This appends your file-to-be-download to a jsp file, thereby not getting downloaded.

    Solution:
    Remove the string return type and change as void. Do not return a string.

    Hope it helps!

  • Hi..
    I am facing problem while downloading a file..
    I am able to do that, if sending simple parameters with url
    like <a href="\\username=123>download

    but when i am trying to send JSON object, its not working, terminating to some unknown URL.

    when I am sending it like
    $http .post('rest/?cd=$scope.OpmMainPageDTO)
    .success(function(data){} )
    .error()

    I am able to send JSON data on server and receive the data back in success, but that file is not downloading on client.

    Please help how to download the file from ModelandView response.

Recent Posts

Agentic Reasoning Design Patterns in AI: Examples

In recent years, artificial intelligence (AI) has evolved to include more sophisticated and capable agents,…

3 weeks ago

LLMs for Adaptive Learning & Personalized Education

Adaptive learning helps in tailoring learning experiences to fit the unique needs of each student.…

4 weeks ago

Sparse Mixture of Experts (MoE) Models: Examples

With the increasing demand for more powerful machine learning (ML) systems that can handle diverse…

1 month ago

Anxiety Disorder Detection & Machine Learning Techniques

Anxiety is a common mental health condition that affects millions of people around the world.…

1 month ago

Confounder Features & Machine Learning Models: Examples

In machine learning, confounder features or variables can significantly affect the accuracy and validity of…

1 month ago

Credit Card Fraud Detection & Machine Learning

Last updated: 26 Sept, 2024 Credit card fraud detection is a major concern for credit…

1 month ago