Reputation: 541
[
{
"name": "AAAAAA",
"date": "28-03-2016",
},
{
"name": "BBBBBB",
"date": "20-12-2016",
},
{
"name": "CCCCCC",
"date": "09-01-2016",
},
{
"name": "DDDDDD",
"date": "21-07-2016",
}
]
My javascript:
var app = angular.module('app', []);
app.service('service', function($http, $q){
var deferred = $q.defer();
$http.get('names.json').then(function(data){
deferred.resolve(data);
});
this.getNames = function() {
return deferred.promise;
}
});
app.controller('FirstCtrl', function($scope, service, $http) {
var promise = service.getNames();
promise.then(function (data) {
$scope.names = data.data;
console.log($scope.names);
}
);
$scope.postfunction = function(data) {
$http({
method: 'POST',
url: 'serwerUrl' ,
data: {"name":$scope.name},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data){
console.log('data success');
});
HTML:
<tbody>
<tr ng-repeat="name in names">
<td>{{name.name}}</td>
<td>{{name.date}}</td>
<td><button ng-click="postfunction(names)">POST</button></td>
</tr>
</tbody>
What I want do is when I click the button "POST" name.name post to server. I try function postfunction(), but it didn't post to server, in my console everything is ok, but name.name don't post to server.
Upvotes: 0
Views: 241
Reputation: 48948
Are you sure that the API takes content type application/x-www-form-urlencoded
? It is best to use the Angular default of application/json
? If you must urlencode the data, use the $httpParamSerializerJQLike Service.
.controller(function($http, $httpParamSerializerJQLike) {
//...
$http({
url: myUrl,
method: 'POST',
data: $httpParamSerializerJQLike(myData),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
});
-- AngularJS Param Serializer API Reference
Upvotes: 0
Reputation: 3758
The $scope.name
you're trying to send isn't defined anywhere.
You'll want to change names
here into name
:
...
<td><button ng-click="postfunction(name)">POST</button></td>
...
and in your postfunction
ditch $scope.name
altogether and do this instead (also use .then instead of .success, .success is deprecated):
$scope.postfunction = function(name) {
$http({
method: 'POST',
url: 'serwerUrl' ,
data: {"name": name},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.then(function(data){
console.log('data success');
});
}
Upvotes: 1