AngularJS > $http service

$http.post server request in AngularJS

How to send data to server using HttpPost method in AngularJS?


In the previous post, we learnt how to get data using $http.get method. In this post, we shall learn how to send HTTP Post request to the server in AngularJS, to do this we shal use $http.post method.

Syntax of $http.post method

The syntax of $http.post method is following

Syntax for AngularJS v1.3.20

 $http.post(url, data, config)
            .success(function (data, status, headers, config) {
            })
            .error(function (data, status, header, config) {
            });


Parameters are

  • url - url to send request to
  • data - data to send
  • config - configuration to use while sending data

Syntax for AngularJS v1.4.8 + (v1.5.0)

$http.post(url, data, config)
.then(
function(response){
// success callback
},
function(response){
// failure callback
}
);

The response object has following properties

  1. data - it can be either string or an object (inserted object)
  2. status - HTTP status ode
  3. headers - header information
  4. config - configuration that was used to send request
  5. statusText - response of HTTP status text


Sending data using $http.post method

In below <script> block, we have created a function named "SendData". In this function, we have prepared a data object that contains the serialzied value from the firstName and lastName property of the html form (explained below). The serialization from JSON to http form data is being using jQuery param function.

As the default header Content-Type set by Angular is json so we need to change to "x-www-form-urlencoded" that is being done using config object in which we have defined headers.

<script>
    var app = angular.module("app", []);
    app.controller("HttpGetController", function ($scope, $http) {

        $scope.SendData = function () {
// use $.param jQuery function to serialize data from JSON
            var data = $.param({
                fName: $scope.firstName,
                lName: $scope.lastName
            });
        
            var config = {
                headers : {
                    'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
                }
            }

            $http.post('/ServerRequest/PostDataResponse', data, config)
            .success(function (data, status, headers, config) {
                $scope.PostDataResponse = data;
            })
            .error(function (data, status, header, config) {
                $scope.ResponseDetails = "Data: " + data +
                    "<hr />status: " + status +
                    "<hr />headers: " + header +
                    "<hr />config: " + config;
            });
        };

    });
</script>

Next, we have called $http.post method by passing respective parameters. This sends asynchrnous request to the server on "/ServerRequest/PostDataResponse" url and the response data is set into $scope.PostDataResponse property.

In below HTML block, we have two text boxes with their ng-model set as firstName and lastName respectively. On click of the button, SendData() function is being called.

<div ng-app="app" ng-controller="HttpGetController">
    <p>First Name: <input type="text" name="firstName" ng-model="firstName" required /></p>
    <p>First Name: <input type="text" name="lastName" ng-model="lastName" required /></p>
    <button ng-click="SendData()">Submit</button>
    <hr />
    {{ PostDataResponse }}
</div>

ASP.NET MVC & C# Server side code

In this action method of the controller, we are simiply retrieving the form data using Request.Form["dataPropertyName"] and retruning back to the caller. 

public ContentResult PostDataResponse()
        {
            return Content("First name: " + Request.Form["fName"] +
                " | Last name: " + Request.Form["lName"]);
        }

Output

AngularJS $http.Post method

 Views: 436197 | Post Order: 60




Write for us






Hosting Recommendations