How to use Ajax calls in AngularJs

In AngularJS you can send AJAX requests in several different ways. These are:

  • AJAX calls via the $http service.
  • JSONP calls via the $http service.

Note: So far only the $http service is covered (both normal AJAX and JSONP), but that is enough to get you started using AJAX in AngularJS.


The $http Service

The $http service is the easiest way to send AJAX calls to your web server. Remember, that AJAX calls cannot be sent to a different domain than the domain from which the HTML page making the AJAX calls is loaded. For instance, if the HTML page was loaded from jenkov.com then that HTML page can only make AJAX calls back to URLs within the jenkov.com domain.

Here is a full AngularJS application with a single $http AJAX example:

<!DOCTYPE html>
<html lang="en">


<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
</head>

<body ng-app="myapp">

  <div ng-controller="MyController" >
    <button ng-click="myData.doClick(item, $event)">Send AJAX Request</button>
    <br/>
    Data from server: {{myData.fromServer}}
  </div>

  <script>
    angular.module("myapp", [])
        .controller("MyController", function($scope, $http) {
            $scope.myData = {};
            $scope.myData.doClick = function(item, event) {

                var responsePromise = $http.get("/angularjs-examples/
json-test-data.jsp"); responsePromise.success(function(data, status, headers,
config) { $scope.myData.fromServer = data.title; }); responsePromise.error(function(data, status, headers,
config) { alert("AJAX failed!"); }); } } ); </script> </body> </html>

Notice how the controller function registered with the module takes two parameters: A $scope object (as always) and an extra $http object. The $http object (or “service”) is used to make AJAX calls.

The the $http.get() function returns a “promise” object. This promise object has a success() and an error()function. By calling these functions and pass a function to them as parameter you can control what happens when the AJAX call finishes. If the AJAX call succeeds (the server sends back an HTTP code between 200 and 209), the function passed to the success() function is executed. If the AJAX call fails (all other codes except for redirects), the function passed to the error() method is executed. The succss() and error() functions are covered in more detail later.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s