0

For my Angularjs application in services I have used Ajax call to get the data and is as follows :

var originalRequest = $.ajax({
                    async : false,
                    url : "/dash/dashboard2ajax.do",
                    type : "POST",
                    data : {
                        action : 'getNetSpendOverTime',
                        customerId : selectedAccTd,
                        carriersId : selectedCarriers,
                        fromDate : formattedFromDate,
                        toDate : formattedToDate
                    },
                    dataType : "json",
                    success : function(originalRequest) {
                        var res = originalRequest;
                        data = res.ResultSet.Response;

                    }
                });

Then I just return (data) from my service and in my controller I am able to get data without any problem. But I realized it is a bad practice and trying to use promises. So I have replaced it as follows:

var originalRequest = $http({
            url: "/dash/dashboard2ajax.do",
            method: "POST",
            data: {action : 'getNetSpendOverTime',
                customerId : selectedAccTd,
                carriersId : selectedCarriers,
                fromDate : formattedFromDate,
                toDate : formattedToDate}
        }).success(function(data, status, headers, config) {
           return (data);
        }).error(function(data, status, headers, config) {
            return(status);
        });

But it is not working. None of the parameters are getting even passed to my action class. Is there any mistake in my syntax?

In my action class, I am accessing the parameters as

String action = request.getParameter("action");

But it is coming as null.

Madasu K
  • 1,813
  • 2
  • 38
  • 72

1 Answers1

1

You're trying to replace jQuery.ajax with AngularJS $http, which has completely different contract. The thing you're calling originalRequest is not in fact any kind of "request object". It's just a Promise (extended with success and error methods). If you want to access the request data outside your success/error handlers, you need to save and pass it separately yourself:

var data = {
    // ...
};
var request = $http({
    data: data,
    // ...
});
return {
    request: request,
    data: data
};

If you need to access it inside the handlers, just get it from the config argument:

$http(...).success(function (data, status, headers, config) {
    var action = config.data.action;
    // ...
});
hon2a
  • 7,006
  • 5
  • 41
  • 55
  • If you're coming from `jQuery` background and trying to learn AngularJS, you need to really read some [documentation](https://docs.angularjs.org/api/ng/service/$http), not just expect things to work like in `jQuery` (they don't). You might try looking [here](http://stackoverflow.com/questions/14994391/thinking-in-angularjs-if-i-have-a-jquery-background/15012542). – hon2a Nov 26 '14 at 09:59