122

I have this piece of jQuery code that works fine cross origin:

jQuery.ajax({
    url: "http://example.appspot.com/rest/app",
    type: "POST",
    data: JSON.stringify({"foo":"bar"}),
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function (response) {
        console.log("success");
    },
    error: function (response) {
        console.log("failed");
    }
});

Now I'm tring to convert this to Angular.js code without any success:

$http({
    url: "http://example.appspot.com/rest/app",
    dataType: "json",
    method: "POST",
    data: JSON.stringify({"foo":"bar"}),
    headers: {
        "Content-Type": "application/json; charset=utf-8"
    }
}).success(function(response){
    $scope.response = response;
}).error(function(error){
    $scope.error = error;
});

Any help appreciated.

Misha Moroshko
  • 148,413
  • 200
  • 467
  • 700
Endless
  • 24,091
  • 10
  • 82
  • 106
  • 3
    Don't know angular.js but maybe faile() is a wrong name of a function? – Bogdan Rybak Aug 26 '12 at 16:15
  • found another simular issue http://stackoverflow.com/questions/11786562/angularjs-asp-net-web-api-cross-domain-issue – Endless Aug 26 '12 at 16:33
  • might have found a solution http://stackoverflow.com/questions/12111936/angularjs-performs-an-options-http-request-for-a-cross-origin-resource need to digg deep... – Endless Aug 26 '12 at 16:36
  • OPTIONS request will be issued by a browser, it will be transparent to AngularJS / your application. If the OPTION succeeds the original request (POST/GET/whatever) will follow and your code will be called back for the main request not the OPTION one. – pkozlowski.opensource Aug 26 '12 at 16:44
  • It is probably not Angular changing the request method to OPTIONS. It is probably your browser checking to see if it can do a CORS request. If you are trying to make a call to a separate domain your browser will make an OPTIONS request first to see if it is allowed. – Ian Mar 01 '13 at 20:41

4 Answers4

202

The AngularJS way of calling $http would look like:

$http({
    url: "http://example.appspot.com/rest/app",
    method: "POST",
    data: {"foo":"bar"}
}).then(function successCallback(response) {
        // this callback will be called asynchronously
        // when the response is available
        $scope.data = response.data;
    }, function errorCallback(response) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
        $scope.error = response.statusText;
});

or could be written even simpler using shortcut methods:

$http.post("http://example.appspot.com/rest/app", {"foo":"bar"})
.then(successCallback, errorCallback);

There are number of things to notice:

  • AngularJS version is more concise (especially using .post() method)
  • AngularJS will take care of converting JS objects into JSON string and setting headers (those are customizable)
  • Callback functions are named success and error respectively (also please note parameters of each callback) - Deprecated in angular v1.5
  • use then function instead.
  • More info of then usage can be found here

The above is just a quick example and some pointers, be sure to check AngularJS documentation for more: http://docs.angularjs.org/api/ng.$http

Sᴀᴍ Onᴇᴌᴀ
  • 7,491
  • 8
  • 27
  • 56
pkozlowski.opensource
  • 116,401
  • 59
  • 321
  • 285
  • 2
    Good to know! however i don't thing its client error i'm dealing with, Angular change the Request method to OPTIONS. think i have to do some server side stuff to support it – Endless Aug 26 '12 at 16:53
  • Yes, I guess you need to sort out server-side problems first. Then you will be able to enjoy full power of angular's $http on the client side. Probably you see an additional OPTIONS request since AngularJS is sending more / different headers as compared to jQuery. – pkozlowski.opensource Aug 26 '12 at 17:15
  • 1
    NOTE: in get "params:" but not "data:" see http://stackoverflow.com/questions/13760070/angularjs-passing-data-to-http-get-request – xander27 Feb 11 '13 at 08:38
  • 5
    `params` and `data` are 2 different things: params end up in the URL (query string) while data - in request body (only for request types that actually can have body). – pkozlowski.opensource Feb 11 '13 at 08:50
  • "Angular change the Request method to OPTIONS. think i have to do some server side stuff to support it " I'm having the same problem, what does angular add that jquery doesnt? – Andrew Luhring Apr 20 '15 at 03:27
1

We can implement ajax request by using http service in AngularJs, which helps to read/load data from remote server.

$http service methods are listed below,

 $http.get()
 $http.post()
 $http.delete()
 $http.head()
 $http.jsonp()
 $http.patch()
 $http.put()

One of the Example:

    $http.get("sample.php")
        .success(function(response) {
            $scope.getting = response.data; // response.data is an array
    }).error(){

        // Error callback will trigger
    });

http://www.drtuts.com/ajax-requests-angularjs/

Vijayaragavan
  • 359
  • 1
  • 3
  • 8
0

You may use this :

Download "angular-post-fix": "^0.1.0"

Then add 'httpPostFix' to your dependencies while declaring the angular module.

Ref : https://github.com/PabloDeGrote/angular-httppostfix

-5

you can use $.param to assign data :

 $http({
  url: "http://example.appspot.com/rest/app",
  method: "POST",
  data: $.param({"foo":"bar"})
  }).success(function(data, status, headers, config) {
   $scope.data = data;
  }).error(function(data, status, headers, config) {
   $scope.status = status;
 });

look at this : AngularJS + ASP.NET Web API Cross-Domain Issue

Community
  • 1
  • 1
hanane
  • 64
  • 1
  • 9
  • 4
    Just a note that $.param is jQuery, so you'll need jQuery loaded to use it. For a jQuery-free example using $http transformRequest interceptor, see http://pastebin.com/zsn9ASkM – notbrain Apr 09 '14 at 21:56
  • @Brian Wait a minute, isn't jQuery a dependency of AngularJS? You'll never have $http without jQuery first being loaded. – jnm2 May 11 '15 at 17:54
  • 2
    @jnm2 - no, jQuery is not a dependency of AngularJS. $http refers to the [Angular $http service component](https://docs.angularjs.org/api/ng/service/$http), not anything from jQuery. AngularJS does have a "jQuery Lite" available for manipulating the DOM, but it's very limited. From [Angular element](https://docs.angularjs.org/api/ng/function/angular.element) - If jQuery is available, angular.element is an alias for the jQuery function. If jQuery is not available, angular.element delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite." – notbrain May 11 '15 at 18:45