ajax

The AngularJS XHR API follows what is commonly known as the Promise interface. As XHRs are asynchronous method calls, the response from the server will come back at an unknown future date and time (hopefully almost immediately!). The Promise interface guarantees how such responses will be dealt with, and allows consumers of the Promise to use them in a predictable manner.

Using GET Request
The create an API '/api/user' which accepts the id as a URL parameter to fetch a user’s information, then the XHR request using Angular’s core $http service would look something like the following:

$http.get('api/user', {
params: {
id: '5'
}
}).success(function(data, status, headers, config) {
// Do something successful.
}).error(function(data, status, headers, config) {
// Handle the error
});

The $http.get method used in the preceding example is one of the method that the core $http AngularJS service provides.

Using POST Request
To make a POST request using AngularJS with the same URL parameters and some POST data, you would do so as follows:

snippet
var postData = {
text: 'long blob of text'
};
// The next line gets appended to the URL as params
// so it would become a post request to /api/user?id=5
var config = {
params: {
id: '5'
}
};
$http.post('api/user', postData, config).success(function(data, status, headers, config) {
// Do something successful
}).error(function(data, status, headers, config) {
// Handle the error
});

Similar convenience methods are provided for most of the common request types, including:
• GET
• HEAD
• POST
• DELETE
• PUT
• JSONP
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +