index.md 1.45 KB
Newer Older
Shane A. Stillwell's avatar
Shane A. Stillwell committed
1 2 3 4 5 6 7 8 9 10 11
---
title: "Getting AngularJS and Zend Framework POST to play nice"
id: 342
date: "2012-07-20T20:29:10-05:00"
tags: 
- AngularJS
- Programming
---

I was simply posting data to the server using this code

12
```javascript
Shane A. Stillwell's avatar
Shane A. Stillwell committed
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
$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) {
    });
};
30
```
Shane A. Stillwell's avatar
Shane A. Stillwell committed
31 32 33 34 35

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`

36
```javascript
Shane A. Stillwell's avatar
Shane A. Stillwell committed
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
$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) {
    });
};
54
```
Shane A. Stillwell's avatar
Shane A. Stillwell committed
55 56

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.