pTutorial

New way to learn Programming

AngularJS AJAX - $http Example

Simple AngularJS Example to get the data form the server $http can be used to get the data from server.

angularJS $http Example

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/
angularjs/1.4.8/angular.min.js"></script>
<body>
 
<div ng-app="ukApp" ng-controller="ukController"> 
<table border="2">
<tr>
<th>Name</th>
<th>City</th>
<th>Country</th>
</tr>
  <tr ng-repeat="x in data">
    <td>{{ x.Name}}</td>
	<td>{{ x.City}}</td>
          <td>{{ x.Country}}</td>
  </tr>
</table>
</div>

<script>
var app = angular.module('ukApp', []);
app.controller('ukController', function($scope, $http) {
    $http.get("data1.php")
    .success(function(response) {
$scope.data = response.studentdata;
});
});
</script> 

 
</body>
</html>

Explanation

You can simply execute this example by deploying the angularjshttp.html and the data.php file on the server.

Everything is same as previous example except these points-

AngularJS will invoke ukController with a $scope and $http object.

$scope is the application object.

$http is an XMLHttpRequest object for requesting external server data.

$http.get() method is used to get the data from server ().

If success, the controller assign the response data to the data property.

http://freeonlinecompiler.ptutorial.com/data1.php file data

{
"studentdata": [
  {
    "Name" : "Umar Farooque",
    "City" : "Delhi",
    "Country" : "India"
  },
   {
    "Name" : "Umar",
    "City" : "Delhi",
    "Country" : "India"
  },
   {
    "Name" : "Rahul",
    "City" : "Delhi",
    "Country" : "India"
  },
  {
    "Name" : "John",
    "City" : "New York city",
    "Country" : "USA"
  }
  
]
}

Ajax Example

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/
angularjs/1.4.8/angular.min.js"></script>
<body>
 
<div ng-app="ukApp" ng-controller="ukController"> 

<table border="2">
<tr>
<th>Name</th>
   <th>City</th>
      <th>Country</th>
</tr>
  <tr ng-repeat="x in data">
    <td>{{ x.Name}}</td>
	    <td>{{ x.City}}</td>
		    <td>{{ x.Country}}</td>
  </tr>
</table>
</div>

<script>
var app = angular.module('ukApp', []);
app.controller('ukController', function($scope, $http) {
    $http.get("data2.php")
    .success(function(response) {
$scope.data = response;
});
});
</script> 

 
</body>
</html>

http://freeonlinecompiler.ptutorial.com/data2.php file data

 [
  {
    "Name" : "Umar Farooque",
    "City" : "Delhi",
    "Country" : "India"
  },
   {
    "Name" : "Umar",
    "City" : "Delhi",
    "Country" : "India"
  },
   {
    "Name" : "Rahul",
    "City" : "Delhi",
    "Country" : "India"
  },
  {
    "Name" : "John",
    "City" : "New York city",
    "Country" : "USA"
  }
  
]

See Also


QUOTES OF THE DAY

Crafty men condemn studies, simple men admire them, and wise use them.

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER