Ashish Panwar Ashish Panwar - 5 months ago 37
jQuery Question

$http.post not working in AngularJS

When I use

$http.get
my code works, but if I use $http.post, I never get the parameters to the request .php file.

This is Service function:

TestPanel.service('MySampleService', function ($http, $q) {
this.getAllPosts = function () {

var def = $q.defer();
$http.post('/data/AJAXRequest.php', 'mydata=1&abcd=2').success(function (data) {
if (data == null)
def.reject('ERROR: DATA IS NULL');
else if (data.HasError)
def.reject('ERROR: ' + data.Message);
else
def.resolve(data);
}).error(function () {
def.reject('ERROR: Sorry, unable to complete your request.');
});

return def.promise;
}
});


And Controller function:

TestController.controller('PostCtrl', ['$scope', '$http', 'MySampleService',
function ($scope, $http, MySampleService) {

function FetchPostsList() {
MySampleService.getAllPosts().then(function (data) {
$scope.lstPosts = data.ResponseData;
$scope.totalRecords = data.totalRecords;
console.info('DATA=' + $scope.lstPosts);
},
function (err) {
console.info('err=' + err);
});
}

FetchPostsList();
}
]);


and
My AJAXRequest.php file

<?php
var_dump($_POST)
?>


if I use $http.post()

Output:

array (size=0)
empty


If i use $http.get()

my output is :

array (size=2)
'mydata' => string '1' (length=1)
'abcd' => string '2' (length=1)


I checked the post in FireBug tool, that its sending data to my php file. but php file getting no params.

If I use $.ajax or $.post my code work and it gives the response.

Answer

What if you specify the content-type in the headers, specifically like this:

$http({
method: 'POST',
url: '/data/AJAXRequest.php',
data: { mydata: 1, abcd: 2 },
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(....);

Found comments relating to PHP specifically from this question: AngularJs $http.post() does not send data

It would seem that Angular sends as application/json by default, which can confuse PHP.

Comments