Introduction:


In this article we will explain what is http post method ($http.post) in angularjs, uses of $http.post method in angularjs and how to use post method ($http.post()) with parameters in angularjs with example.

 

Description:


In angularjs we use $http service to send or get data from remote server using browsers XMLHttpRequest object. The $http.POST() services are used to send the data to the server  a specific URL and expects the resource at that URL to handle the request in other words we can say that  POST method is used to Insert new data based on given URL and it is one of the shortcut method in $http service.

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) {
            });

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

 

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

Parameters are

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

 

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 and age 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("HttpPostController", function ($scope, $http) {
 
            $scope.SendData = function () {
                //use $.param jQuery function to serialize data from JSON
                var data = $.param({
                    fName: $scope.firstName,
                    lName: $scope.lastName,
                    age: $scope.age
                });
 
                var config = {
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
                    }
                }
 
                $http.post('/Home/PostData', data,config)
                .then(function (data, status,headers, config) {
                    $scope.PostDataResponse =data['data'];
                })
                .catch(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 "/Home/PostData" url and the response data is set into $scope.PostDataResponse property.

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

<div class="container">        
        <div ng-app="app" ng-controller="HttpPostController">
            <p>First Name: <input type="text" name="firstName" ng-model="firstName" required /></p>
            <p>Last Name: <input type="text" name="lastName" ng-model="lastName" required /></p>
            <p>Age: <input type="text" name="age" ng-model="age" required /></p>
            <button ng-click="SendData()">Submit</button>
            <hr />
            First Name:{{ PostDataResponse.fname }}<br />
            Last Name:{{ PostDataResponse.lname }}<br />
            Age:{{ PostDataResponse.age }}<br />
 
           
        </div>
    </div>  

ASP.NET MVC & C# Server side code

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

[HttpPost]
        public ActionResult PostData()
        {
var Result = new      {fname=Request.Form["fName"],lname=Request.Form["lName"],age=Request.Form["age"]};
            return Json(Result,JsonRequestBehavior.AllowGet);
        }

 

Let’s see an example:

 

Index.cshtml

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>http.Post</title>
 
    <script src="/Scripts/jquery-3.1.1.js"></script>
    <script src="/Scripts/angular.js"></script>   
    <script>
        var app = angular.module("app", []);
        app.controller("HttpPostController", function ($scope, $http) {
            $scope.SendData = function () {
                //use $.param jQuery function to serialize data from JSON
                var data = $.param({
                    fName: $scope.firstName,
                    lName: $scope.lastName,
                    age: $scope.age
                });
 
                var config = {
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
                    }
                }
                $http.post('/Home/PostData', data,config)
                .then(function (data, status,headers, config) {
                    $scope.PostDataResponse =data['data'];
                })
                .catch(function (data, status,header, config) {
                    $scope.ResponseDetails = "Data: " + data+
                        "<hr />status: " + status +
                        "<hr />headers: " + header +
                        "<hr />config: " + config;
                });
            };
 
        });
    </script>
</head>
<body>
    <div class="container">       
        <div ng-app="app" ng-controller="HttpPostController">
            <p>First Name: <input type="text" name="firstName" ng-model="firstName" required /></p>
            <p>Last Name: <input type="text" name="lastName" ng-model="lastName" required /></p>
            <p>Age: <input type="text" name="age" ng-model="age" required /></p>
            <button ng-click="SendData()">Submit</button>
            <hr />
            First Name:{{ PostDataResponse.fname }}<br />
            Last Name:{{ PostDataResponse.lname }}<br />
            Age:{{ PostDataResponse.age }}<br />
 
           
        </div>
    </div>  
</body>
</html>

 

HomeController.cs

using MVC_Tutorials.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVC_Tutorials.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {              return View();
        }
        [HttpPost]
        public ActionResult PostData()
        {
            var Result = new {fname=Request.Form["fName"],lname=Request.Form["lName"],age=Request.Form["age"]};
            return Json(Result,JsonRequestBehavior.AllowGet);
        }        
    }     }

 

OutPut:

AngularJS Http Post Method ($http.post) with Parameters Example

I hope this article will help to you.

0 comments


Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

you may also like