Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery ajax request works, same AngularJS ajax request doesn't

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;
    });
});
like image 843
Pavel Avatar asked Sep 23 '13 19:09

Pavel


1 Answers

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.

like image 109
Miichi Avatar answered Oct 11 '22 23:10

Miichi