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.

5
  • 3
    Don't know angular.js but maybe faile() is a wrong name of a function? Commented Aug 26, 2012 at 16:15
  • found another simular issue stackoverflow.com/questions/11786562/…
    – Endless
    Commented Aug 26, 2012 at 16:33
  • might have found a solution stackoverflow.com/questions/12111936/… need to digg deep...
    – Endless
    Commented Aug 26, 2012 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. Commented Aug 26, 2012 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
    Commented Mar 1, 2013 at 20:41

4 Answers 4

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

5
  • 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
    Commented Aug 26, 2012 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. Commented Aug 26, 2012 at 17:15
  • 1
    NOTE: in get "params:" but not "data:" see stackoverflow.com/questions/13760070/…
    – xander27
    Commented Feb 11, 2013 at 8: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). Commented Feb 11, 2013 at 8: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? Commented Apr 20, 2015 at 3: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/

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

3
  • 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 pastebin.com/zsn9ASkM
    – notbrain
    Commented Apr 9, 2014 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
    Commented May 11, 2015 at 17:54
  • 2
    @jnm2 - no, jQuery is not a dependency of AngularJS. $http refers to the Angular $http service component, not anything from jQuery. AngularJS does have a "jQuery Lite" available for manipulating the DOM, but it's very limited. From 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
    Commented May 11, 2015 at 18:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.