Angularjs ajax tutorial

In AngularJS, we can send Ajax request in several ways:

1. AJAX calls via the $http service.
2. JSONP calls via the http service.
3. REST type calls.

 
We are explaining here ajax call via the $http service. AngularJS provides the $http service for reading data from remote servers. Let us discuss $http service and its method in brief.

AngularJS $http service:

In AngularJS, $http service makes a request to the server and returns a response.

AngularJS $http service methods:

$http.get(url, config): Used to perform Http GET request.
$http.post(url, data, config): Used to perform Http POST request.
$http.put(url, data, config): Used to perform Http PUT request.
$http.delete(url, config): Used to perform Http DELETE request.
$http.head(url, config): Used to perform Http HEAD request.

AngularJS $http service response object’s properties:

config: It is the object used to generate the request.
data: It is a string, or an object, carrying the response from the server.
headers: It is a function used to get header information.
status: It is a number which defines the HTTP status.
statusText: It is a string which defines the HTTP status.

Config Parameter:

method: Used to set the HTTP method for the request.
url: Used to set the URL of the AJAX call.
params: Used to set any additional request parameters to be appended to the URL query string.
headers: Used to set any additional HTTP headers.
timeout: Used to set the timeout for the AJAX call.
cache: Used to enable XHR GET request caching.
transformRequest: Used to set a function which can transform the request object before it is sent to the server.
transformResponse: used to set a function which can transform the response sent back from the server, before it is passed to application.

Example Explanation:

First include the AngularJS library in the application. The ng-app directive initializes the application. In appCtrl controller we pass one more parameter $http, to make an ajax call. The $http service makes an ajax call using get() method and sets response to message property.

Example:

welcome.txt:

Hello AngularJS Students

test.htm:

<!DOCTYPE html>
<html>
<script 
 src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">
</script>
<body>
<h2>AngularJS Ajax $http service example.</h2>
<div ng-app="testApp" ng-controller="appCtrl"> 
<h3>{{message}}</h3>
</div>
 
<script>
var app = angular.module('testApp', []);
app.controller('appCtrl', function($scope, $http) {
  $http.get("welcome.txt")
  .then(function(response) {
      $scope.message= response.data;
  });
});
</script>
 
</body>
</html>

Output:

angularjsajax1