Ajax requests with Angularjs

April 29, 2015
by Rahil Shaikh

In many applications client is required to make requests to remote http servers to fetch data, or as we say make ajax requests, AngularJs provides $http service for making ajax requests to remote servers.

In this tutorial we just want to demonstrate a simple get and post request in angular js using the $http service.

We will also learn to do the same in the preferred way, which is wrapping the $http in another service or factory.

General Syntax
//get request
      $http.get(<url>).success(function(response, status, headers, config){
           //process success scenario.
      }).error(function(err, status, headers, config){
           //process error scenario.
      });

      //post request
      $http.post(<url>,<request_data>).success(function(response, status, headers, config){
           //process success scenario.
      }).error(function(err, status, headers, config){
           //process error scenario.
      });

      //delete request
       $http.delete(url, [config]).success(function(response, status, headers, config){ //here config is an optional object to pass delete prams
           //process success scenario.
      }).error(function(err, status, headers, config){
           //process error scenario.
      });

response variable contains the data returned by the API.
The syntax for put is same as post except you have to use the respective method.

$http service returns a promise object with success and error functions.
It supports actions such as get, post, put, delete and jsonp.

DEMO  DOWNLOAD

Get request example.
app.js
(function(){
    angular.module('myapp',[])
   
    //define controller and inject $http service as dependency.
    .controller('axajCtrl',['$http','$scope',function($http,$scope){
        $http.get('extras/data.json').success(function(response){ //make a get request to mock json file.
            $scope.data = response; //Assign data received to $scope.data
        })
        .error(function(err){
            //handle error
        })
    }])

})();
Wrapping $http request in another service/factory (Preferred way).

The recommended way to make an ajax call with angular js is to wrap $http request into a factory and then use it to serve data. This makes your code more organised and separates the concerns. Also it allows you to pre-process the received data and use it in multiple controllers.

app.js
(function(){
    angular.module('myapp',[])
   
    //afactory to consume webservices and return data to controllers.
    .factory('webServices',['$http',function($http){
        return {
            getFriends : function(){
                return  $http.get('extras/data.json').then(function(response){ //wrap it inside another promise using then
                            return response.data.friends;  //only return friends
                        });
            }
        }
    }])
    //define controller and inject webServices service as dependency.
    .controller('prefferedCtrl',['webServices','$scope',function(webServices,$scope){
        webServices.getFriends().then(function(response){
            $scope.friends = response; //Assign data received to $scope.data
        });
    }])


})();

Here if you notice I’m using the then method instead on success and error,this is because success returns the original $http promise where as by using then we can return a new promise, this helps us to process the data inside the factory and return only the required information.

Its perfectly fine to use success instead of then if you want the factory to return the original $http promise

Below is the html file for the above demo.

index.html
<html>
    <head>
    </head>
    <body ng-app='myapp' >
       
        <h2>get ajax request with angular js</h2>
        <div ng-controller='axajCtrl'>{{data}} <br></div>
        ======================================================</br>
        <h2>Doing it in prefered way (Wrapping $http in a factory)</h2>
        <div ng-controller='prefferedCtrl'>{{friends}}</div>
    </body>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
    <script src="js/app.js"></script>
</html>

Angular js also allows you to set custom headers using the $http.defaults object.

eg: $http.defaults.headers.common[‘foo’] = ‘Bar’;

This was a basic introduction to the Angular’s $http service, it can do a lot more then what we have seen over here.
Head over to the documentation to dive deeper.

About

Engineer. Blogger. Thinker. Loves programming and working with emerging tech. We can also talk on Football, Gaming, World Politics, Monetary Systems.

Get notified on our new articles

Subscribe to get the latest on Node.js, Angular, Blockchain and more. We never spam!
First Name:
Email:

3 comments

  1. varma
    |

    Hi Rahul,
    I am new to angularJs, I have seen several demo’s regarding angularJs, it is easily understanding to beginners..
    I need a simple demo, form having two text fields and file uploading with specific formats like( png,jpg etc) in a single form

    Thanks in Advanced.

    Ravi Varma.

  2. Jag
    |

    Thank you for the article. It is really great to learn from you regarding ajax and angularjs. BTW, I happened to find a beginner’s video which covers $http, CORS, AJAX etc. in simple presentation here: https://www.youtube.com/watch?v=7-ahq_hxWQo Hopefully it helps for other readers who are interested.

  3. |

    Thanks for the wonderful article, Can you please give some more example with JSON format & encryption methods.

Leave a Comment