I'm learning AngularJS and trying to build front-end system that gets data from Wordpress.
On the back-end side everything seems to be set up properly and when I use jQuery ajax request it gets the data without problems.
jQuery.ajax({
type: 'POST',
url: '/wp-admin/admin-ajax.php',
data: {
action: 'getdataajax'
},
success: function(data, textStatus, XMLHttpRequest){
console.log(data);
},
error: function(MLHttpRequest, textStatus, errorThrown){
console.log(errorThrown);
}
});
But when I try to do the same thing with AngularJS, it does not work. I'm trying to replicate the ajax request with code like this:
myApp.factory('productsData', function($http, $log) {
return {
getProducts: function(successcb) {
return $http({
method: 'POST',
url: '/wp-admin/admin-ajax.php',
data: {action: 'getdataajax'}
}).success(function(data, status, headers, config) {
successcb(data);
$log.info(data, status, headers(), config)
}).error(function(data, status, headers, config) {
$log.warn(data, status, headers(), config)
});
},
};
});
If I log it, it outputs 0. What am I missing?
Thanks for your help.
P.S. Controller looks like this:
myApp.controller('ProductsController', function ProductsController($scope, productsData) {
$scope.sortorder = 'name';
// $scope.products = productsData.products;
// $scope.products = productsData.getProducts();
productsData.getProducts(function(products){
$scope.products = products;
});
});
In the angularjs code, use params:
instead of data:
.
In jquery the object supplied to the data:
config setting is converted to a query string (?key1=val1&key2=value2) unless you set processData: false
. in angularjs, you have to use params:
to get a query string, data:
is sent as json or string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With