Angular.js

AngularJS Ajax Call Example

Hello readers, in this basic example, developers are going to call the Ajax in the angular framework while reading the data from the server.

1. Introduction

AngularJS is a JavaScript MVC or Model-View-Controller framework developed by Google that lets developers build well structured, easily testable, and maintainable front-end applications. The angular library provides multiple out-of-box services and angular ajax is one of them.

The angular framework provides the $http services and is used to do the HTTP request to retrieve the desired data from the server. The server would then make a database call to retrieve the required records in the JSON format. In angular ajax, developers can send the Ajax requests in multiple ways, such as:

  • Angular Ajax calls through $http service
  • JSONP calls through $http service
  • REST API calls

Fig. 1: Ajax request in Angular
Fig. 1: Ajax request in Angular

1.1 What is HTTP service?

$http is the core angular service used to do the HTTP requests to communicate with the remote servers and retrieve the required data through the browser’s XMLHttpRequest object or the JSON. To access the angular ajax in a controller, developers will have to use the $scope object i.e. $http service retrieve the data from the server in the following way.

$http basic syntax

$http({
	method : "GET",
	url : "resource/data/countrylist.json"
}).then(function(response) {
	$scope.countries = response.data;
});

Where:

  • countrylist.json is the sample file containing the country list
  • The $http service makes an Ajax call and set the result in the countries property. Later, this model object draws the table in HTML

Do note, the $http service returns the success() and failure() promise objects that take call back functions as parameters.

1.1.1 HTTP Service Methods

There are several functions of calling the $http service. Below is the list of built-in functions available with this service:

  • $http.get(url, config): This is frequently used method to read the records from the server
  • $http.post(url, data, config) and $http.put(url, data, config): These methods accept an input argument to be sent to the server in JSON string
  • $http.delete(url, config): This method deletes the record or the information from the server
  • $http.head(url, config): This method allows the client and the server to pass an additional information with the request or the response object

Developers can refer to this link to have a detailed information on $http service. These new APIs make developer’s life easier, really! But it would be difficult for a beginner to understand this without an example. Therefore, let us create a simple application using the $http service.

2. AngularJS Ajax Call Example

Here is a step-by-step guide for implementing the ajax in angular applications.

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8 and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.

2.2 Project Structure

Firstly, let’s review the final project structure if you are confused about where you should create the corresponding files or folder later!

Fig. 2: Application Project Structure
Fig. 2: Application Project Structure

2.3 Project Creation

This section will show how to create a Java-based Maven project with Eclipse. In Eclipse Ide, go to File -> New -> Maven Project.

Fig. 3: Create Maven Project
Fig. 3: Create Maven Project

In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Just click on next button to proceed.

Fig. 4: Project Details
Fig. 4: Project Details

Select the ‘Maven Web App’ Archetype from the list of options and click next.

Fig. 5: Archetype Selection
Fig. 5: Archetype Selection

It will ask you to ‘Enter the group and the artifact id for the project’. We will enter the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Fig. 6: Archetype Parameters
Fig. 6: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you see, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>AngularAjaxEx</groupId>
	<artifactId>AngularAjaxEx</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
</project>

Let’s start building the application!

3. Application Building

Let’s create an application to understand the basic building blocks of the angular ajax.

3.1 Load the AngularJS framework

Since it is a pure JavaScript framework, we should add its reference using the <script> tag.

<script type="text/javascript" src="resource/js/angular_v1.6.0.js"></script>

3.2 Define the AngularJS application

Next, we will define the angular application using the <ng-app> directive.

index.jsp

<div ng-app = "myApp">
 ...
</div>

3.3 Creating an AngularJS Controller

The JavaScript file i.e. ajax.js includes the myCtrl function as the “controller” in the Model-View-Controller. This JavaScript code is retrieving the countries list from the countrylist.json using an ajax ask from the server. Here, we are injecting the $http in the angular controller and assigning the response to the countries list.

ajax.js

var ajax = angular.module('myApp', []);

ajax.controller('myCtrl', function($scope, $http) {

	$http({
		method : "GET",
		url : "resource/data/countrylist.json"
	}).then(function(response) {
		$scope.countries = response.data;
	});
});

3.4 Complete Application

Complete the above steps and I will show you how to use the angular ajax with real-life practices. Let’s see the code snippet.

index.jsp

<!DOCTYPE html>
<html>
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <title>AngularJs Ajax</title>
      
      <!-- AngularJs Javascript File -->            
      <script type="text/javascript" src="resource/js/angular_v1.6.0.js"></script>
      <script type="text/javascript" src="resource/js/ajax.js"></script>
      
      <!-- Bootstrap Css -->      
      <link rel="stylesheet" type="text/css" href="https://www.webcodegeeks.com/wp-content/litespeed/localres/aHR0cHM6Ly9tYXhjZG4uYm9vdHN0cmFwY2RuLmNvbS8=bootstrap/4.0.0/css/bootstrap.min.css">      
   </head>
   <body>
      <h1 align="center" class="text-primary">AngularJs Ajax Example</h1>
      <hr/>
      <div ng-app="myApp" ng-controller="myCtrl" class="container">
         <table class="table table-bordered table-hover">
            <thead>
               <tr>
                  <th>Id</th>
                  <th>Continent Id</th>
                  <th>Name</th>
               </tr>
            </thead>
            <tbody>
               <tr ng-repeat="c in countries">
                  <td>{{ c.id }}</td>
                  <td>{{ c.continent_id }}</td>
                  <td>{{ c.country_name }}</td>
               </tr>
            </tbody>
         </table>
      </div>
   </body>
</html>

4. Run the Application

As we are ready for all the changes, let us compile the project and deploy the application on the Tomcat7 server. To deploy the application on Tomat7, right-click on the project and navigate to Run as -> Run on Server.

Fig. 7: How to Deploy Application on Tomcat
Fig. 7: How to Deploy Application on Tomcat

Tomcat will deploy the application in its web-apps folder and shall start its execution to deploy the project so that we can go ahead and test it in the browser.

5. Project Demo

Open your favorite browser and hit the following URL. The output page using the angular ajax will be displayed.

http://localhost:8085/AngularAjaxEx/

Server name (localhost) and port (8085) may vary as per your Tomcat configuration.

Fig. 8: Angular Ajax
Fig. 8: Angular Ajax

That’s all for this post. Happy Learning!!

6. Conclusion

In this section, developers learned how to create a simple application using the angular ajax. Developers can download the sample application as an Eclipse project in the Downloads section.

7. Download the Eclipse Project

This was an example of Ajax in the angular framework.

Download
You can download the full source code of this example here: AngularAjaxEx

Yatin

The author is graduated in Electronics & Telecommunication. During his studies, he has been involved with a significant number of projects ranging from programming and software engineering to telecommunications analysis. He works as a technical lead in the information technology sector where he is primarily involved with projects based on Java/J2EE technologies platform and novel UI technologies.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button