Endless Endless - 2 months ago 10
jQuery Question

from jquery $.ajax to angular $http

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.

Answer

The AngularJS way of calling $http would look like:

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

or could be written even simpler using shortcut methods:

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

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)

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

Comments