In this tutorials, we are going to learn about how to make AJAX calls in AngularJs Framework. In Angular http service is used to make the AJAX calls. In the previous tutorials we have discussed all predefined services and custom services, if you are not coming from those tutorials, it is recommended to see once.
What is AJAX?
AJAX stands for Asynchronous Javascript And Xml.
AJAX is a client side programming technique, used to communicate with server asynchronously.
This technique is initially identified and used by google team.
Advantages of AJAX :
- Quick Response.
- Reduced the burden on server.
- Reduce the network traffic.
- Comfortable for the userd, no need to wait more time for response.
- Partial page updates.
Implementing AJAX in programming :
- AJAX is a client side programming technique.
- It is implemented with the help of Java script
- If we implement AJAX calls with basic Java script, it will be a difficult and time consuming.
- In order to make AJAX programming easy, there are several Javascript libraries are available.
AngularJs
JQuery
DOJO
MooTools Etc.,
AJAX as Angular http :
AngularJs Framework provides special service called $http to implement AJAX programming.
By using Angular http service, we can communicate with server asynchronously.
How to use Angular http service :
The following is the sytax to use the angular $http service;
$http({
url: “resourceurl”,
method: “GET/POST”
}).then(function Succes(response) {
// Handling Success Data
}, function Error(response) {
// Handling Error Data
});
Angular http Example :
[html]
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<style>
li{
height: 30px;
width: 200px;
padding: 5px;
border:1px solid green;
}
</style>
<body>
<div ng-app="myApp" ng-controller="ajaxController">
<h3>AngularJs AJAX With JSON Calls</h3>
<ul>
<li ng-repeat="x in myData">
{{x}}
</li>
</ul>
</div>
<script>
var app = angular.module(‘myApp’, []);
app.controller(‘ajaxController’, function ($scope, $http) {
$http({
url: "books.php",
method: "GET"
}).then(function Succes(response) {
$scope.myData = response.data;
}, function Error(response) {
alert(response.data);
});
});
</script>
</body>
</html>
[/html]
Resource file : books.php
[php]
<?php
$booksArray = array();
array_push($booksArray, "Java");
array_push($booksArray, "C");
array_push($booksArray, "C++");
array_push($booksArray, "Spring");
array_push($booksArray, "Hibernate");
array_push($booksArray, "AngularJS");
array_push($booksArray, "JQuery");
echo json_encode($booksArray);
?>
[/php]
Output :
AngularJs AJAX With JSON Calls
- Java
- C
- C++
- Spring
- Hibernate
- AngularJS
- JQuery
Happy Learning 🙂