AngularJS AJAX – $http

AJAX (Asynchronous JavaScript and XML) is crucial for creating dynamic web applications that fetch and display data without reloading the page. In AngularJS, the $http service provides an easy way to make AJAX requests and interact with APIs.

In this guide, you’ll learn how to use AngularJS $http to fetch, post, and manipulate data effectively. Explore more coding tutorials at The Coding College, your trusted resource for programming knowledge.

What Is $http in AngularJS?

The $http service is a core AngularJS service for making HTTP requests to a remote server. It simplifies the process of sending and receiving data, supports promises, and integrates seamlessly with AngularJS’s two-way data binding.

Features of $http

  1. Supports All HTTP Methods: GET, POST, PUT, DELETE, etc.
  2. Handles Promises: Uses .then() for success and .catch() for errors.
  3. Customizable: Allows headers, parameters, and configurations.
  4. JSON Handling: Simplifies JSON data exchange.

Syntax

$http({
    method: 'HTTP_METHOD',
    url: 'API_ENDPOINT',
    data: {}, // Optional, used for POST/PUT requests.
    headers: {} // Optional, used for custom headers.
}).then(function successCallback(response) {
    // Handle success.
}, function errorCallback(error) {
    // Handle error.
});

Making a GET Request

Example: Fetching Data

<div ng-app="myApp" ng-controller="myCtrl">
    <h3>Post Titles:</h3>
    <ul>
        <li ng-repeat="post in posts">{{ post.title }}</li>
    </ul>
</div>

<script>
    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope, $http) {
        $http.get('https://jsonplaceholder.typicode.com/posts')
            .then(function(response) {
                $scope.posts = response.data;
            })
            .catch(function(error) {
                console.error("Error fetching data: ", error);
            });
    });
</script>

Output: Displays a list of post titles fetched from the API.

Making a POST Request

Example: Submitting Data

<div ng-app="myApp" ng-controller="myCtrl">
    <h3>Add a Post:</h3>
    <form ng-submit="addPost()">
        <input type="text" ng-model="newPost.title" placeholder="Title" required>
        <textarea ng-model="newPost.body" placeholder="Body" required></textarea>
        <button type="submit">Submit</button>
    </form>
</div>

<script>
    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope, $http) {
        $scope.newPost = {};
        $scope.addPost = function() {
            $http.post('https://jsonplaceholder.typicode.com/posts', $scope.newPost)
                .then(function(response) {
                    console.log("Post added successfully:", response.data);
                })
                .catch(function(error) {
                    console.error("Error adding post:", error);
                });
        };
    });
</script>

Output: Sends the form data to the server and logs the response.

Custom Headers

Example: Adding Authorization

$http({
    method: 'GET',
    url: 'https://api.example.com/data',
    headers: {
        'Authorization': 'Bearer your_token_here'
    }
}).then(function(response) {
    console.log("Data:", response.data);
}).catch(function(error) {
    console.error("Error:", error);
});

Handling Errors

Error handling is essential for a smooth user experience.

Example: Using .catch()

$http.get('https://api.example.com/nonexistent')
    .then(function(response) {
        console.log("Data:", response.data);
    })
    .catch(function(error) {
        console.error("An error occurred:", error.statusText);
    });

Using $http in a Service

Services are ideal for encapsulating API calls for reuse.

Example: Creating an API Service

var app = angular.module('myApp', []);
app.service('ApiService', function($http) {
    this.getData = function() {
        return $http.get('https://jsonplaceholder.typicode.com/posts');
    };
});

app.controller('myCtrl', function($scope, ApiService) {
    ApiService.getData().then(function(response) {
        $scope.posts = response.data;
    });
});

Complete Example

<div ng-app="myApp" ng-controller="myCtrl">
    <h3>Post Titles:</h3>
    <ul>
        <li ng-repeat="post in posts">{{ post.title }}</li>
    </ul>
    <h3>Add a Post:</h3>
    <form ng-submit="addPost()">
        <input type="text" ng-model="newPost.title" placeholder="Title" required>
        <textarea ng-model="newPost.body" placeholder="Body" required></textarea>
        <button type="submit">Submit</button>
    </form>
</div>

<script>
    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope, $http) {
        $scope.newPost = {};

        // Fetch posts
        $http.get('https://jsonplaceholder.typicode.com/posts')
            .then(function(response) {
                $scope.posts = response.data;
            })
            .catch(function(error) {
                console.error("Error fetching posts:", error);
            });

        // Add a post
        $scope.addPost = function() {
            $http.post('https://jsonplaceholder.typicode.com/posts', $scope.newPost)
                .then(function(response) {
                    console.log("Post added:", response.data);
                })
                .catch(function(error) {
                    console.error("Error adding post:", error);
                });
        };
    });
</script>

Best Practices

  1. Use Services for API Calls
    Encapsulate $http calls in services for reusability.
  2. Error Handling
    Always handle errors using .catch() or similar methods.
  3. Avoid Hardcoding URLs
    Use constants or configuration files for API endpoints.
  4. Optimize for Performance
    Cache responses when possible to reduce API calls.

Conclusion

The AngularJS $http service simplifies AJAX operations, making it easy to fetch and manipulate data. By using $http effectively, you can build dynamic and interactive web applications.

Leave a Comment