call ajax request in angularjs

How to call AJAX Request in AngularJs?

I am going to share the code sample for the ways of calling AJAX Request using $http.get(), $http.post(), $http.put(), $http.post(), $http.delete() or $http.head() methods in angularjs.

Table of Content
  1.  $http service
  2.  $http function
  3.  $http as a function
  4.  The config parameter
  5.  The success() And error() functions in angularjs Ajax
The angularjs AJAX Request manage in different types. The types re given below.
  1. AJAX call over the $http services.
  2. REST API Call over the $http services.
  3. JSON Call over the $http services.
The $http services is a way of sending AJAX request on the web servers. The $http and $scope both are managed by the controller function.

The functions over the $http service that is called $http function. The function list as given below.
  1. $http.get(url, config);
  2. $http.post(url, data, config);
  3. $http.put(url, data, config);
  4. $http.delete(url, config);
  5. $http.head(url, config);
Here we can also used the $http services as function. Its look like below code.

{{
      var httpAsFunction = $http(config);        
}}

The config parameter handle the parameters that are

  1. URL
  2. Methods
  3. parameter 
  4. header etc.

The success() function handle the success data and the error() function handle the error response that is show in the below example. 

The example code as given below.

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
        angular.module("myapp", [])
          .controller("MyController", function ($scope, $http) {
              $scope.result = {};

              $scope.register = function (item, event) {
                  var response = $http.get("url/angularjs-ajaxcall/json-data");

                  response.success(function (data, status, headers, config) {
                      $scope.result.rltdata = data.title;
                  });

                  response.error(function (data, status, headers, config) {
                      alert("Faild to call AJAX Request!!!");
                  });
              }
          });
</script>
</head>
<body ng-app="myapp">
    <div ng-controller="MyController">
         Register Response Result from Server: {{ rltdata.data }} <br>
        <button ng-click="register(item, $event)">Register AJAX Request</button>
    </div>
</body>
</html>

The out put look like below images


ANIL SINGH

Hey! I'm Anil Singh. I author this blog. I'm Active Blogger, Programmer. I love learning new technologies, programming, blogging and participating the forum discussions more...
My Blogs - http://www.code-sample.com and http://www.code-sample.xyz
My Books - Google Amazon and Flipkart Book Store!

You Might Also Like
Post a Comment
www.code-sample.com/. Powered by Blogger.