from jquery $.ajax to angular $http

The question:

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

    url: "",
    type: "POST",
    data: JSON.stringify({"foo":"bar"}),
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function (response) {
    error: function (response) {

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

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

Any help appreciated.

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

The AngularJS way of calling $http would look like:

    url: "",
    method: "POST",
    data: {"foo":"bar"}
}).then(function successCallback(response) {
        // this callback will be called asynchronously
        // when the response is available
        $ =;
    }, 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:

$"", {"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

Method 2

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,


One of the Example:

        .success(function(response) {
            $scope.getting =; // is an array

        // Error callback will trigger

Method 3

You may use this :

Download “angular-post-fix”: “^0.1.0”

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

Ref :

Method 4

you can use $.param to assign data :

  url: "",
  method: "POST",
  data: $.param({"foo":"bar"})
  }).success(function(data, status, headers, config) {
   $ = data;
  }).error(function(data, status, headers, config) {
   $scope.status = status;

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

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment