Getting AngularJS and Zend Framework POST to play nice
Hold on Cowboy
This blog post is pretty old. Be careful with the information you find in here. It's likely dead, dying, or wildly inaccurate.
I was simply posting data to the server using this code
$scope.submit = function() {
console.log($scope.newTitle + ' is the new title');
$http({
url: '/api/idea/method/add',
method: 'POST',
data: {
title: $scope.newTitle,
description: $scope.newDescription
},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data, status) {
})
.error(function(data, status) {
});
};
But I was getting a JSON object submitted and therefore using Zend’s _getParam('title')
could not pick up the title in the post.
The answer was to use jQuery’s $.param
function. So now I surround the data JSON with $.param
$scope.submit = function() {
console.log($scope.newTitle + ' is the new title');
$http({
url: '/api/idea/method/add',
method: 'POST',
data: $.param({
title: $scope.newTitle,
description: $scope.newDescription
}),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data, status) {
})
.error(function(data, status) {
});
};
I know AngularJS has a way to change the data transform function, but I’m too lazy right now to figure out how to do it.
Did this help you out? It took me a few days to piece together all this information together, I hope this saves you some time (who knows, maybe the future me will be thankful I wrote this down). Let me know your thoughts. [email protected]