Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

6 Answers 6

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

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

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 at 16:23
    
@ppetermann have you checked the edit history of the question before downvoting.. –  entre Jan 20 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

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

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.