With the advancement of technology, there is a growing need for dynamic and responsive web pages. One popular way to achieve this is through the use of AJAX (Asynchronous JavaScript and XML). AngularJS provides a powerful tool for implementing AJAX functionality in web applications: the AJAX - $http service.
In this article, we will discuss the AJAX - $http service, its methods, properties, and how to make GET and POST requests using it. Before starting, let's see what AngularJS is.
AngularJS
AngularJS is a famous JavaScript framework that is used for building web applications. It is preferred for creating Single Page Application projects (SPA). It helps extend HTML DOM with many additional attributes making it more responsive for user purposes. It is an open-source based framework used by thousands of developers all over the world.
AngularJS provides a useful tool for implementing AJAX functionality in web applications. Before we move on to understand it, first, we should be familiar with AJAX.
AJAX
AJAX stands for Asynchronous JavaScript and XML. It is a technique that allows web developers to develop dynamic web applications. It helps to fasten the applications by preventing the entire page from being refreshed. It is done by only rendering the parts of a web page that are updated.
AJAX includes the following technologies: JavaScript, XML, and the XMLHttpRequest object. It is used in modern web development to develop fast and dynamic web applications. It is used with many programming languages, including PHP, JavaScript, and Python.
AJAX - $http
The AngularJS framework provides the $http service, which allows developers to make AJAX requests within an AngularJS application. This service provides a powerful API for handling responses and errors, making it easy to communicate with a server and update parts of the web page without a full page refresh.
Methods
There are several methods provided by $http to make different types of requests:
GET request: The $http.get() is used to make a GET request to a server. The GET request is used to retrieve data from the server.
POST request: The $http.post() is used to make a POST request to a server. It submits data to the server and creates a new resource.
PUT request: The $http.put() is used to make a PUT request to a server. It is used to update an existing resource on the server.
DELETE request: The $http.delete() is used to make a DELETE request to a server. It is used to delete the resources on the server.
HEAD request: The $http.head() is used to make a HEAD request to a server. It is similar to a GET request, but it only retrieves the headers of a resource and not the actual content.
JSONP request: The $http.jsonp() is used to make a JSONP request to a server. JSONP or JSON with Padding refers to a technique used to bypass the same-origin policy, which is a security feature of web browsers that prevents making requests to a different domain.
PATCH request: The $http.patch() is used to make a PATCH request to a server. It is used to update only a part of an existing resource on the server, while the PUT request updates the whole resource.
Syntax
Let's now discuss the syntax for the GET and POST requests:
GET request
As we have learned above, a GET request retrieves the data from the server. It is done with the help of $http.get() method. Following is the syntax for the same.
$http.get(url, [config]);
The first argument of the get() method takes the URL of the server, and the second argument is an optional config object. This config object can set headers, timeout, and other options for the request. The delete(), head(), and jsonp() methods have similar syntax.
POST request
The POST request to the server is used to submit the data to the server and creates a new resource. It is done with the help of $http.post() method. Following is the syntax for the same.
$http.post(url, data, [config]);
The first argument takes the URL of the server, the second argument takes the data to be sent, and the third argument is an optional config object that can be used to set headers, timeout, and other options for the request. The put() and patch() methods have similar syntax.
Returns
The $http service in AngularJS returns a promise, which is an object that represents the completion or failure of an operation and its resulting value. It has the following properties:
data: This property is used to get the response data.
headers: It provides the headers of the current response. It is returned as an object with key-value pairs. The keys specify header names, and the values are header values.
config: It represents the object containing the configuration of the current request, such as the method, URL, headers, and data.
status: It defines the HTTP status code of the current response, like 404 for not found error.
statusText: It is the HTTP status text of the response in the form of a string.
Let's now see the implementation of the AJAX - $http service using an example.
Implementation
To implement the AJAX-$http, we have created a To-do app. We need a server to send and receive data. We can create a REST API JSON server following these steps:
Open the command prompt and run this command: npm install -g json-server. This will create a server and a file db.json.
Open the file db.json, and replace the file with some data following this syntax:
Last, Start the server by writing: json-server --watch db.json.
Now follow these steps to create a to-do list:
Create an HTML file that uses AngularJS and W3.CSS for styling. Include both of them.
Provide the <body> element with the ng-app and ng-controller attributes, which define the AngularJS module and controller that handles the logic of the application.
Create a form with an input element and a button, which are used to add new items to the list. Set the following attributes:
The ng-model attribute binds the value of the input element to a variable in the controller. Set its value as newTodo, which will be used later.
The ng-click attribute binds the button to a function that is called when the button is clicked. Provide it with the addTodo() function.
Create an unordered list and provide the ng-repeat attribute to <li>, which is used to loop through the items and display them on the page.
In the script tag, create an AngularJS module named exampleApp and declare a controller angularCtrl within the module, which is provided in the body element.
Create the functions addTodo and removeToDo, which are used to make requests to the server running on "http://localhost:3000/todos/", which we have created before.
Use the $http service and define the GET, POST, and DELETE requests following the syntax as shown in the code.
Code
<!DOCTYPE html>
<html>
<head>
<!--
Include W3.CSS using this link
-->
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<!--
Custom styling
-->
<style>
.cont {
width: 500px;
height: 1000px;
background-color: peachpuff;
}
.btn {
display: inline-block;
padding: 10px 30px 8px 30px;
}
.input {
width: 300px;
display: inline-block;
}
</style>
<!--
Including AngularJS using script tag
-->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
</head>
<body ng-app="exampleApp" ng-controller="angularCtrl">
<div class="w3-container cont ">
<h1>To-Do List</h1>
<form>
<input type="text" class="w3-input w3-border w3-round input" ng-model="newTodo" placeholder="Add a new item"
ng-required="true">
<button class="w3-button w3-black w3-round btn" ng-click="addTodo()">
Add
</button>
</form>
<ul>
<li ng-repeat="todo in todos" class="w3-margin-top">
{{todo.Name}}
<button ng-click="removeTodo(todo)" class="w3-button w3-red w3-round w3-small">
Delete
</button>
</li>
</ul>
</div>
<script>
var app = angular.module('exampleApp', []);
app.controller('angularCtrl', ['$scope', '$http', function ($scope, $http) {
var url = "http://localhost:3000/todos/";
// GET request to fetch items
$http.get(url)
.then(res => {
$scope.todos = res.data;
});
// POST request to add items
$scope.addTodo = () => {
var newTodo = { Name: $scope.newTodo };
$http.post(url, newTodo).then(res => {
return $http.get(url);
})
.then(res => $scope.todos = res.data);
};
// DELETE request to remove items
$scope.removeTodo = todo => {
$http.delete(url + todo.id).then(res => {
return $http.get(url);
})
.then(res => $scope.todos = res.data);
};
}]);
</script>
</body>
</html>
Output
After we add a new item:
After deleting the items:
Frequently Asked Questions
How is AngularJS different from ReactJS?
The main difference between both is that AngularJS is a full-featured framework, while React is a library for building user interfaces. This means that React is focused on rendering UI, while Angular is focused on building complete client-side applications.
What is AJAX with respect to AngularJS?
AJAX, also known as Asynchronous JavaScript and XML, creates fast and dynamic web applications. It is mostly used to communicate with a server and retrieve or update data without having to refresh the entire page.
What are some important features of AngularJS?
AngularJS allows you to sync data between your UI and your JavaScript code easily. It separates the application into different components (model, view, and controller) to make it easier to develop and maintain. It also provides support for routing.
How can we send an AJAX request?
We can send an AJAX request in JavaScript using the XMLHttpRequest object, which allows you to open a connection to a server, send a request, and handle the response.
What are the benefits of using AJAX?
AJAX allows us to retrieve and update data without refreshing the entire page. It only updates the necessary parts of a web page, thus reducing the load of the server. You can make real-time updates without refreshing the page.
Conclusion
In this article, we have discussed AngularJS and AJAX - $http service provided by AngularJS. We have learned the different methods for calling them and the implementation for the same.
If you are interested to learn further about AngularJS, you can check out our other blogs: