41

I want to send multiple parameters using angularjs HTTP post service.

Here is client side code:

$http.post("http://localhost:53263/api/Products/", [$scope.product, $scope.product2]).
        then(function (data, status, headers, config) { alert("success") },
             function (data, status, headers, config) { alert("error") });

Here is server side code:

// POST api/<controller>
public void Post([FromBody]Product product,[FromBody]Product product2)
{
    var productRepository = new ProductRepository();
    var newProduct = productRepository.Save(product);
}

But when I make the post I get error. Any idea what I am doing wrong?

2

11 Answers 11

44

Client Side

Data needs to be grouped in an object array as payload - Indata:

var Indata = {'product': $scope.product, 'product2': $scope.product2 };

Pass the payload through $http.post as the second argument:

$http.post("http://localhost:53263/api/Products/", Indata).then(function (data, status, headers, config) { 
    alert("success"); 
},function (data, status, headers, config) { 
    alert("error"); 
});

Server Side

Create a Data Transfer Object(DTO) class as such:

public class ExampleRequest {
   public string product {get; set;};
   public string product2 {get; set;};
}

The class below accepts DTO with the same property names which the payload is carrying.

public void Post(ExampleRequest request)
{
    var productRepository = new ProductRepository();
    var newProduct = productRepository.Save(request.product);
}

In above class, request contains 2 properties with values of product and product2

1
  • OP is using what appears to be web-api specific C# syntax, which means that at most, only one object can be read from the body of a POST request. Calling $http.post("url", payload) is going to append payload to the body of the request. Prior to web api, this was fine, but now, it will NOT parse values from this object. You either need a single receiving object to de-serialize to or you need send some data via other methods.
    – godskook
    Aug 1, 2018 at 14:24
36

Consider a post url with parameters user and email

params object will be

 var data = {user:'john', email:'john@email.com'};
    $http({
      url: "login.php",
      method: "POST",
      params: data
    })
4
  • 21
    You should add an explanation of what you are doing, even if this is pretty straightforward. Aug 30, 2016 at 18:19
  • 4
    Yep, I just came across this and while it may seem useful to others. I have no clue of what exactly to do with this. -1
    – Hoi_A
    Apr 17, 2017 at 15:01
  • 1
    yes it worked, this way, it makes difference. however $http.post(url, data) doesn't
    – Ram
    Jun 17, 2017 at 17:24
  • 1
    @Ram there is a difference. In $http.post(url, data), "data" is here the body of the POST request. In the above example ..params: data.. "data" are the query params.
    – Elio
    Dec 5, 2018 at 15:33
6

It depends on what is your backend technology. If your backend technology accepting JSON data. data:{id:1,name:'name',...}

otherwise, you need to convert your data best way to do that creating Factory to convert your data to id=1&name=name&...

then on $http define content-type. you can find full article @https://www.bennadel.com/blog/2615-posting-form-data-with-http-in-angularjs.htm

$http({
    method: 'POST',
    url: url,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    transformRequest: function(obj) {
        var str = [];
        for(var p in obj)
        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
        return str.join("&");
    },
    data: {username: $scope.userName, password: $scope.password}
}).success(function () {});

ref:How do I POST urlencoded form data with $http in AngularJS?

!important about encodeURIComponent(obj[p]) will transfer object the way implicit. like a date value will be converted to a string like=>'Fri Feb 03 2017 09:56:57 GMT-0700 (US Mountain Standard Time)' which I don't have any clue how you can parse it at least in back-end C# code. (I mean code that doesn't need more than 2-line) you can use (angular.isDate, value.toJSON) in date case to convert it to more meaningful format for your back-end code.

I'm using this function to comunicating to my backend webservices...

 this.SendUpdateRequest = (url, data) => {
            return $http({
                method: 'POST',
                url: url,
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                transformRequest: function (obj) { return jsontoqs(obj); },
                data: { jsonstring: JSON.stringify(data) }
            });
        }; 

and bellow code to use it...

webrequest.SendUpdateRequest(
  '/Services/ServeicNameWebService.asmx/Update',
  $scope.updatedto)
  .then(
      (res) => { /*/TODO/*/ },
      (err) => { /*/TODO/*/ }
);

in backend C# I'm using newtonsoft for deserializing the data.

0
4

You can only send 1 object as a parameter in the body via post. I would change your Post method to

public void Post(ICollection<Product> products)
{
}

and in your angular code you would pass up a product array in JSON notation

4
  • 2
    really there is no way to send multiple params in angularjs $http?
    – Michael
    Jun 20, 2015 at 18:16
  • not in the body unfortunately but you can pass strings or numerical data in the url instead but not sure if that's a an option for you if Product is a complex object. Edit: just to note, this isn't a limitation specific to angular, it's HTTP
    – Arrakis
    Jun 20, 2015 at 18:18
  • Do you have any idea can I send simple type(string,int etc...) in POST budy?
    – Michael
    Jun 20, 2015 at 18:20
  • 2
    yes you can send a string or int in the post body just as you do above but again you are limited to only 1. if you need to send multiple strings / ints you'll have to use POST to your API with your parameters attached to the URL. this is a more common approach for GET though (ie querying for a product using it's ID. As Dev-One posts you can also create a DTO to house the properties you need to transmit. That way you get multiple parameters encapsulated in a single object
    – Arrakis
    Jun 20, 2015 at 18:25
4

If you're using ASP.NET MVC and Web API chances are you have the Newtonsoft.Json NuGet package installed.This library has a class called JObject which allows you to pass through multiple parameters:

Api Controller:

public class ProductController : ApiController
{
    [HttpPost]
    public void Post(Newtonsoft.Json.Linq.JObject data)
    {
        System.Diagnostics.Debugger.Break();

        Product product = data["product"].ToObject<Product>();
        Product product2 = data["product2"].ToObject<Product>();

        int someRandomNumber = data["randomNumber"].ToObject<int>();
        string productName = product.ProductName;
        string product2Name = product2.ProductName;
    }
}

public class Product
{
    public int ProductID { get; set; }
    public string ProductName { get; set; }
}

View:

<script src="~/Scripts/angular.js"></script>
<script type="text/javascript">
    var myApp = angular.module("app", []);
    myApp.controller('controller', function ($scope, $http) {

        $scope.AddProducts = function () {
            var product = {
                ProductID: 0,
                ProductName: "Orange",
            }

            var product2 = {
                ProductID: 1,
                ProductName: "Mango",
            }

            var data = {
                product: product,
                product2: product2,
                randomNumber:12345
            };

            $http.post("/api/Product", data).
            success(function (data, status, headers, config) {
            }).
            error(function (data, status, headers, config) {
                alert("An error occurred during the AJAX request");
            });
        }
    });
</script>
<div ng-app="app" ng-controller="controller">
    <input type="button" ng-click="AddProducts()" value="Get Full Name" />
</div>
2
  var headers = {'SourceFrom':'web'};
  restUtil.post(url, params, headers).then(function(response){

You can also send (POST) multiple params within {} and add it.

1
import { HttpParams} from "@angular/common/http";
let Params= new HttpParams();
Params= Params.append('variableName1',variableValue1);
Params= Params.append('variableName2',variableValue2);

http.post<returnType>('api/yourApiLocation',variableValue0,{headers, params: Params})
0

Here is the direct solution:

// POST api/<controller>
[HttpPost, Route("postproducts/{product1}/{product2}")]
public void PostProducts([FromUri]Product product, Product product2)
{
    Product productOne = product; 
    Product productTwo = product2; 
}

$scope.url = 'http://localhost:53263/api/Products/' +
                 $scope.product + '/' + $scope.product2
$http.post($scope.url)
    .success(function(response) {
        alert("success") 
    })
    .error(function() { alert("fail") });
};

If you are sane you do this:

var $scope.products.product1 = product1;
var $scope.products.product2 = product2;

And then send products in the body (like a balla).

1
  • Great answer! I dont't want to create an other dto class to do that.
    – gsubiran
    Mar 30, 2016 at 12:38
0

You can also send (POST) multiple params within {} and add it.

Example:

$http.post(config.url+'/api/assign-badge/', {employeeId:emp_ID,bType:selectedCat,badge:selectedBadge})
    .then(function(response) {
        NotificationService.displayNotification('Info', 'Successfully Assigned!', true);
    }, function(response) {
});

where employeeId, bType (Badge Catagory), and badge are three parameters.

0
var name = $scope.username;
var pwd = $scope.password;

var req = {
    method: 'POST',
    url: '../Account/LoginAccount',
    headers: {
        'Content-Type': undefined
    },
    params: { username: name, password: pwd }
}

$http(req).then(function (responce) {
    // success function
}, function (responce) {
    // Failure Function
});
1
  • By Using above code, we can send POST with multiple params in Angular JS Apr 11, 2016 at 6:29
0

add the transformRequest as below to send multiple params to backend

var jq = jQuery.noConflict();
            var transform = function(data) {
                return jq.param(data);
            };
            var config = {
                headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                },transformRequest: transform
            };

      var params={
            blogPostJson:JSON.stringify($scope.blogPost),
            publish:$scope.blogPost.active
        };
        var url = "${createLink(controller : 'cms', action : 'saveBlog')}";
            $http.post(url,params, config).then(function onSuccess(response) {
                var data = response.data;
               // var status = response.status;
                if (data.error) {
                    alert('error :' + data.error);
                } else {
                  //  alert('Success');

                }

            }).catch(function onError(response) {
                //console.log ("Unable to save Alcohol information");
            });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.