Join the Stack Overflow Community
Stack Overflow is a community of 6.4 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I am new to angularJS, and for a start, I thought to develop a new application using only AngularJS.

I am trying to make an AJAX call to the server side, using $http from my Angular App.

For sending the parameters, I tried following:

$http({
    method: "post",
    url: URL,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    data: $.param({username: $scope.userName, password: $scope.password})
}).success(function(result){
    console.log(result);
});

This is working but, it is using jQuery as well near, $.param. For removing dependency on jQuery, I tried,

data: {username: $scope.userName, password: $scope.password}

But this seemed to fail. Then I tried params:

params: {username: $scope.userName, password: $scope.password}

But this also seemed to fail. Then I tried JSON.stringify:

data: JSON.stringify({username: $scope.userName, password: $scope.password})

I found these possible answers to my quest, but was unsuccessful. Am I doing something wrong.? I am sure, AngularJS would provide this functionality. But how.?

share|improve this question
    
I don't know what is actual problem but did you try this $http({method: 'post', url: URL, data: {username: $scope.userName, password: $scope.password}}); – Mritunjay Jul 12 '14 at 7:06
1  
Your first method should work, is $scope.userName defined? why didn't you try data: data? – Kevin B Jul 12 '14 at 7:12
    
@KevinB: sorry.. I have made the correct edit. – Veer Shrivastav Jul 12 '14 at 7:36
    
@mritunjay: sorry.. I have made the edit.. I was trying the same. – Veer Shrivastav Jul 12 '14 at 7:37
    
@Veer did it work or still you having issues? – V31 Jul 12 '14 at 12:12
up vote 283 down vote accepted
+50

I think you need to do is to transform your data from object not to JSON string, but to url params.

From Ben Nadel's blog.

By default, the $http service will transform the outgoing request by serializing the data as JSON and then posting it with the content- type, "application/json". When we want to post the value as a FORM post, we need to change the serialization algorithm and post the data with the content-type, "application/x-www-form-urlencoded".

Example from here.

$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 () {});
share|improve this answer
3  
works for me..thanks! – AdityaSaxena Sep 22 '14 at 23:23
19  
Thank you for not using JQuery! – OverMars Jan 12 '15 at 17:50
1  
what if I need to submit multipart/form-data? – Dejell Jan 13 '15 at 7:57
1  
As long as angular embeds jqLite under angular.element, you can simply return angular.element.param(obj); – Vicary Jan 26 '15 at 15:43
3  
@Vicary Keep in mind that param() is not implemented in jqLite - code.angularjs.org/1.3.14/docs/api/ng/function/angular.eleme‌​nt – Alex Pavlov Mar 25 '15 at 0:35

URL-encoding variables using only AngularJS services

With AngularJS 1.4 and up, two services can handle the process of url-encoding data for POST requests, eliminating the need to manipulate the data with transformRequest or using external dependencies like jQuery:

  1. $httpParamSerializerJQLike - a serializer inspired by jQuery's .param() (recommended)

  2. $httpParamSerializer - a serializer used by Angular itself for GET requests

Example usage

$http({
  url: 'some/api/endpoint',
  method: 'POST',
  data: $httpParamSerializerJQLike($scope.appForm.data), // Make sure to inject the service you choose to the controller
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded' // Note the appropriate header
  }
}).success(function(response) { /* do something here */ });

See a more verbose Plunker demo


How are $httpParamSerializerJQLike and $httpParamSerializer different

In general, it seems $httpParamSerializer uses less "traditional" url-encoding format than $httpParamSerializerJQLike when it comes to complex data structures.

For example (ignoring percent encoding of brackets):

Encoding an array

{sites:['google', 'Facebook']} // Object with array property

sites[]=google&sites[]=facebook // Result with $httpParamSerializerJQLike

sites=google&sites=facebook // Result with $httpParamSerializer

Encoding an object

{address: {city: 'LA', country: 'USA'}} // Object with object property

address[city]=LA&address[country]=USA // Result with $httpParamSerializerJQLike

address={"city": "LA", country: "USA"} // Result with $httpParamSerializer
share|improve this answer
    
How can we use this on $resource inside a factory ? – stilllife Oct 9 '15 at 10:17
2  
Should be $http.({... instead of` $http.post({... – Carlos Granados Nov 7 '15 at 14:30
    
@CarlosGranados Thanks for noticing. Corrected this typo here and in the Plunker demo. – Boaz Nov 7 '15 at 16:15
    
This worked perfectly after migrating from jQuery to AngularJS – zero298 Feb 18 at 22:47
2  
This is the AngularJS-specific answer I was looking for. I wish the poster would select this as the best answer. – Marty Chang May 1 at 4:08

All of these look like overkill (or don't work)... just do this:

$http.post(loginUrl, "userName=" + encodeURIComponent(email) +
                     "&password=" + encodeURIComponent(password) +
                     "&grant_type=password"
).success(function (data) {
share|improve this answer
8  
Finally some common sense – JLewkovich Jul 28 '15 at 17:53
    
Just THANK YOU! – Alex Pogiba Oct 21 '15 at 13:40
    
Won't this send the request with the wrong content-type header? – Phil Jul 22 at 5:24
    
It worked for me... not sure what the header was, but the request worked and it allowed to successfully authenticate. Why don't you test it out and let us know. – Serj Sagan Jul 23 at 6:51
1  
@Phil I guess it might depend on the server, I got bad request, until i added { headers: {'Content-Type': 'application/x-www-form-urlencoded'} } as the config arg, or supply use the $http(config) constructor like moices' answer shows. Either way this is superior to the accepted answer since it does not introduce some magic transformation and does not require the user of some auxillary service. Thanks! – Mr. Bungle Nov 17 at 20:05

The problem is the JSON string format, You can use a simple URL string in data:

$http({
    method: 'POST',
    url: url,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    data: 'username='+$scope.userName+'&password='+$scope.password
}).success(function () {});
share|improve this answer
    
I don't think that would work. – Veer Shrivastav Sep 6 '15 at 5:56
4  
you have to use encodeURIComponent($scope.userName) to url encode the data or your parameters will get corrupted if user enters value like "&myCustomParam=1" – Ivan Hušnjak Sep 9 '15 at 18:28
1  
this is the only answer that has worked for me! I skipped success, but $http format is good – xenteros Jul 19 at 11:38

If it is a form try changing the header to:

headers[ "Content-type" ] = "application/x-www-form-urlencoded; charset=utf-8";

and if it is not a form and a simple json then try this header:

headers[ "Content-type" ] = "application/json";
share|improve this answer
    
Not receiving anything. I still received blank $_POST array.! – Veer Shrivastav Jul 20 '14 at 11:36
    
is this $http call in your controller? – V31 Jul 25 '14 at 17:36
    
one more thing is your server end php? – V31 Jul 25 '14 at 18:07
    
I have found a solution for the same are you still getting the problem @Veer? – V31 Jul 29 '14 at 5:20

you need to post plain javascript object, nothing else

           var request = $http({
                method: "post",
                url: "process.cfm",
                transformRequest: transformRequestAsFormPost,
                data: { id: 4, name: "Kim" }
            });

            request.success(
                function( data ) {
                    $scope.localData = data;
                }
            );

if you have php as back-end then you will need to do some more modification.. checkout this link for fixing php server side

share|improve this answer
    
thats exactly NOT what he asked for, he specifically asked how he can get them as x-www-form-urlencoded, because he is running into issues with json stuff posted. – ppetermann Jan 16 '15 at 16:23
    
@ppetermann have you checked the edit history of the question before downvoting.. – entre Jan 20 '15 at 13:07

This worked for me. I use angular for front-end and laravel php for back-end. In my project, angular web sends json data to laravel back-end.

This is my angular controller.

var angularJsApp= angular.module('angularJsApp',[]);
angularJsApp.controller('MainCtrl', function ($scope ,$http) {

    $scope.userName ="Victoria";
    $scope.password ="password"


       $http({
            method :'POST',
            url:'http://api.mywebsite.com.localhost/httpTest?callback=JSON_CALLBACK',
            data: { username :  $scope.userName , password: $scope.password},
            headers: {'Content-Type': 'application/json'}
        }).success(function (data, status, headers, config) {
            console.log('status',status);
            console.log('data',status);
            console.log('headers',status);
        });

});

This is my php back-end laravel controller.

public function httpTest(){
        if (Input::has('username')) {
            $user =Input::all();
            return  Response::json($user)->setCallback(Input::get('callback'));
        }
    }

This is my laravel routing

Route::post('httpTest','HttpTestController@httpTest');

The result in browser is

status 200
data JSON_CALLBACK({"username":"Victoria","password":"password","callback":"JSON_CALLBACK"}); httpTesting.js:18 headers function (c){a||(a=sc(b));return c?a[K(c)]||null:a}

There is chrome extension called postman. You can use to test your back-end url whether it is working or not. https://chrome.google.com/webstore/detail/postman-rest-client/fdmmgilgnpjigdojojpjoooidkmcomcm?hl=en

hopefully, my answer will help you.

share|improve this answer

From the $http docs this should work..

  $http.post(url, data,{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
    .success(function(response) {
         // your code...
     });
share|improve this answer
    
@Kevin i am not sure about this but..once when i tried sending a string it showed me an error – maandoo Jul 12 '14 at 7:10
    
@KevinB Fine..I got it..i think headers are needed to be changed while sending a string..stackoverflow.com/a/20276775/2466168 – maandoo Jul 12 '14 at 7:20
1  
Note that sending the correct headers would not affect the data which will still need to be urlencoded, one way or another. – Boaz Sep 1 '15 at 8:55
    
data is still sent in json you must encode the data into x-www-form-urlencoded just adding a header is not enough – Wendell Muntslag Feb 28 at 16:10
    
Didn't work for me for angular 1.5 – Dimuthu Sep 2 at 6:51

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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