AngularJS Ajax

AngularJS allow the $http control which works as a service to read data from the server. The server makes a database call to allow the actual records In AngularJS Ajax you can send AJAX requests in many different ways such as:

  • Ajax calls via the $http service
  • JSON calls via the $http service
  • REST type calls

This point can be noted: So far the $http service is covered both normal AJAX and JSON, but that is more to get you started using AJAX in AngularJS and the REST Application Programming Interface (APIs) is not necessary to understand to start using AJAX.

Angularjs Ajax calls

The $http Service

The $http service is the simple way to send AJAX calls to your web server. Always remember. Ajax calls cannot be sent to a different domain from which the Hyper Text Markup Language (HTML) page making the AJAX calls is loaded. For example, the Hyper Text Markup Language (HTML) page was loaded from J2EEbarin.com then that HTML page can only make Ajax calls back to URLs within the J2EEbarin.com domain.

Here we are giving the complete AngularJS app with a single $http Ajax call.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
    <script src="https://ajax.j2eebrain.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
</head>
 
<body ng-app="myapp">
 
  <div ng-controller="MyWebsite" >
    <button ng-click="myData.doClick(item, $event)">Send AJAX Request</button>
    <br/>
    Data from server: {{myData.fromServer}}
  </div>
 
  <script>
    angular.module("myapp", [])
        .controller("MyWebsite", function($scope, $http) {
            $scope.myData = {};
            $scope.myData.doClick = function(item, event) {
 
                var responseImportant = $http.get("/angularjs-instance/json-test-data.jsp");
 
                responseImportant.success(function(data, status, headers, footer, config) {
                    $scope.myData.fromServer = data.title;
                });
                responseImportant.error(function(data, status, headers, footer, config) {
                    alert("AJAX failed!");
                });
            }
 
 
        } );
  </script>
 
</body>
 
</html>

Note: How the controller function registered with the module takes two parameters: A scope object and an extra $http object. The $http object or service is used to make Ajax calls.

The $http.get() function returns a “important” object. This important object has a success () and an error () function. Through calling these functions and pass a function to them as a parameter you can control what happens when the Ajax calls completed. If the Ajax calls successes the server sends back an HTTP code between 300 and 309 the function passed to the success() function is executed. If the Ajax calls not success all other codes except for redirects the function passed to the error () method. The method’s success () and error () functions are covered in more conclusion later.

READ  Angularjs Module

AJAX request in Angularjs

AngularJS needs data in JavaScript Object Notation (JSON) format. Before the data is ready $http can be utilized to get the data from the server in the following manner:

function employeeController($scope,$http) {
var url="data.txt";
   $http.get(url).success( function(response) {
                           $scope.employee = response;
                        });
}

For example:In this code the file data.txt contains employee details. $http service makes an Ajax call and sets response to its property employee. Employee model can be used to draw tables in HTML.

data.txt

[
{
"Name" : "Meraj Ansari",
"ID" : 1563453,
"Salary" : "15,000"
},
{
"Name" : "Deepak Gupta",
"ID" : 2013533,
" Salary " : "12,000"
},
{
"Name" : "Himanshi Thakur",
"ID" : 3125755,
"Salary" : "16,000"
},
{
"Name" : "Ankita Tiwari",
"ID" : 4215755,
"Salary" : "12000"
}
]

testAngularJS.html

<html>
<head>
<title>Angular JS Includes</title>
<style>
table, th , td {
  border: 1px solid grey;
  border-collapse: collapse;
  padding: 5px;
}
table tr:nth-child(odd) {
  background-color: #f2f2f2;
}
table tr:nth-child(even) {
  background-color: #ffffff;
}
</style>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app="" ng-controller="studentController">
<table>
   <tr>
      <th>Name</th>
      <th>ID</th>
              <th>Salary</th>
   </tr>
   <tr ng-repeat="employee in employee">
      <td>{{ employee.Name }}</td>
      <td>{{ employee.ID }}</td>
              <td>{{ employee.Salary }}</td>
   </tr>
</table>
</div>
<script>
function employeeController($scope,$http) {
var url="data.txt";
   $http.get(url).success( function(response) {
                           $scope.employee = response;
                        });
}
</script>
<script src="http://ajax.j2eebrain.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
</body>
</html>

To execute this example, you need to deploy testAngularJS.html and the data.txt file to a web server.