15

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;
    });
});
Pavel
  • 153
  • 1
  • 4
  • How are you using this in your controller ? – tymeJV Sep 23 '13 at 19:33
  • Updated the post. I've tried different ways. Commented as well. None of them works. Sorry – Pavel Sep 23 '13 at 19:35
  • Add it to the question please, pasting code in comments is rather ugly. – tymeJV Sep 23 '13 at 19:35
  • Seems that nobody else tried to use angular with wordpress. I made some server testing. Php responds properly. Also, if I hardcode the data into the factory - it works fine. To be honest, all of this is rather weird. – Pavel Sep 23 '13 at 19:45
  • Can you use `console.dir(arguments)` to see all arguments and values in your success function? In the networks tab in chrome dev tools you can see the request, are you getting the same data back? – Jason Goemaat Sep 23 '13 at 20:16

1 Answers1

29

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.

Miichi
  • 1,739
  • 1
  • 14
  • 16